ISO C++ forbids declaration of 'myStruct'

2019-09-19 13:41发布

问题:

Here is my code DeviceClass.cpp:

...
#include "myHeader.h"

class DeviceClass : public DeviceClassBase {
private:
myClass::myStruct Foo;

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

myClass myclass(Foo);
...
};

This is myClass from the myHeader.h 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 get this error:

: error: ISO C++ forbids declaration of 'myStruct' with no type
: error: expected ';' before '.' token
: error: 'myStruct' is not a type
: In member function 'virtual void DeviceClass::Init()':
: error: '((DeviceClass*)this)->DeviceClass::myclass' does not have class type

Where a m I going wrong?

I can only edit the DeviceClass.cpp file.

回答1:

Statements are not valid at the class level, they are only valid inside of functions or methods. Perhaps you meant to write a default constructor instead. This is somewhat complicated by the fact that myClass has no default constructor (your explicitly-declared copy constructor suppresses the implicit default constructor), so you need to construct it in the initializer list. You'll need a static factory function to create the required myStruct argument with the values you want.

class DeviceClass : public DeviceClassBase
{
public:
    DeviceClass();

private:
    static myClass::myStruct create_myStruct();

    myClass myclass;
};

myClass::myStruct DeviceClass::create_myStruct()
{
    myClass::myStruct Foo;

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

    return Foo;
}

DeviceClass::DeviceClass() : myclass(create_myStruct()) { }


标签: c++ class object