所以我test.h
包含:
#ifndef TEST_H_
#define TEST_H_
class test {
public:
int value;
};
#endif /* TEST_H_ */
和我的main.cpp
:
#include "test.h"
class Magic {
test x;
x.value = 2; // Syntax error
};
int main () {
test y;
y.value = 2; // Works fine
return 0;
}
为什么会这样?
答案 0 :(得分:3)
在c++
的类定义中分配这样的值不是有效语法。该错误与标题或其他任何内容无关。尝试将所有内容放在一个文件中,您将看到相同的行为。
如果您想为Magic
的每个实例将x.value的默认初始化设置为2,请在Magic
的构造函数中定义它:
class Magic {
test x;
Magic() {
x.value = 2;
}
};