ISO C++ forbids declaration of 'myStruct' with no type

余生颓废 提交于 2020-01-07 08:13:28

问题


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()) { }


来源:https://stackoverflow.com/questions/27684721/iso-c-forbids-declaration-of-mystruct-with-no-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!