不在main中时,无法从另一个头文件调用函数

时间:2016-11-30 12:52:36

标签: c++

所以我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;
}

为什么会这样?

1 个答案:

答案 0 :(得分:3)

c++的类定义中分配这样的值不是有效语法。该错误与标题或其他任何内容无关。尝试将所有内容放在一个文件中,您将看到相同的行为。

如果您想为Magic的每个实例将x.value的默认初始化设置为2,请在Magic的构造函数中定义它:

class Magic {
  test x;
  Magic() {
    x.value = 2;
  }
};