------------------------------------------------------------------------------
MC logo
Plain Structs
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Plain Structs] [Point With Struct] [C++ Point Class] [Linked List (Structs)] [Linked List (Classes)] [C++ v. Java Classes I] [Prime Generator Algorithm] [Fast Primes Generator]
struct.cpp
/*
 * These are basic structs.  Data, but no operations.
 */
#include <iostream>
#include <string>
using namespace std;

/* Struct is like a class w/o methods. */
struct fred {
        int m;
        string str;
        double d;
};
/* Notice the semicolon above. */

/* Print a fred, preceded by a message. */
void pfred(string t, struct fred *fr)
{
        cout << t << ": [ m = " << fr->m << ", str = " << fr->str
             << ", " << fr->d << " ]" << endl;
}

int main()
{
        /* This declares a variable f1 which is a fred, and initializes it
           to the values indicated. */
        struct fred f1 = { 40, "Howdy", 5.498 };

        /* This declares two variables, an uninitialized fred and a pointer
           to a fred object. */
        struct fred f2, *fp;

        f2 = f1;
        pfred("f1", &f1);
        pfred("f2", &f2);

        f2.m += 10;
        f2.str += " there";
        f2.d = 16.0001;
        pfred("AA", &f2);

        fp = &f1;
        fp->m = -55;
        fp->str.erase(3);
        fp->d = 111.111;
        pfred("ZZ", &f1);
}