【问题标题】:ISO C++ forbids declaration of 'myStruct' with no typeISO C++ 禁止声明没有类型的“myStruct”
【发布时间】:2014-12-29 07:02:32
【问题描述】:

这是我的代码 DeviceClass.cpp:

...
#include "myHeader.h"

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

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

myClass myclass(Foo);
...
};

这是来自 myHeader.h 文件的 myClass:

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

但这编译失败。 我收到此错误:

: 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

我哪里出错了?

我只能编辑 DeviceClass.cpp 文件。

【问题讨论】:

  • 看起来不像是有效的 C++。在类声明中间赋值给实例变量???
  • 看起来您正在接近 C++,只需输入代码并查看会发生什么。这是使用这种语言可能犯的最严重的错误;由于某些原因,C++ 根本无法通过实验来学习(无论您多么聪明),您需要先阅读手册。从stackoverflow.com/q/388242/320726 挑选一本好书并从头到尾阅读。如果您这样做,您的未来将非常感激。
  • 为什么不先从your previous question解决问题?

标签: c++ class object


【解决方案1】:

语句在类级别无效,它们仅在函数或方法内部有效。也许您打算改为编写一个默认构造函数。这有点复杂,因为myClass 没有默认构造函数(显式声明的复制构造函数抑制了隐式默认构造函数),因此您需要在初始化列表中构造它。您需要一个 static 工厂函数来创建所需的 myStruct 参数以及您想要的值。

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

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多