Initialising a struct which is member of class

2019-06-11 15:45发布

问题:

Here is my code:

...
#include "myheader.h"

myClass::myStruct Foo;

Foo.one = 1;
Foo.two = 2;

myClass myclass(Foo);
...

This is my class from the header file:

class myClass : baseClass{
public:
struct myStruct {
myStruct():
one(0),
two(0){}
int one;
int two;
};
myClass(const myStruct &mystruct);
};

But this is failing to compile, I think I am accessing the elements one and two in the proper way... I get this error:

: expected constructor, destructor, or type conversion before '.' token .

Where a m I going wrong?

回答1:

Foo.one = 1;

This is a statement, and it needs to go inside of a function or method definition. Statements cannot appear by themselves at the top level of a source file.

Try putting this code inside of a function, for example the entry point main():

int main() {
    myClass::myStruct Foo;

    Foo.one = 1;
    Foo.two = 2;

    myClass myclass(Foo);

    return 0;
}