这是我的代码:
main.cpp
#include "foo.h"
int main()
{
return 0;
}
foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo();
int bar;
}
#endif
foo.cpp
#include "foo.h"
Foo::Foo()
{
bar = 3;
}
编译它会给我以下错误:
'bar'的多重定义
但是我在定义 bar
的头文件周围包含了保护,因此它怎么能被定义多次呢?
最佳答案
这是因为 foo.h
中类声明 foo
末尾缺少分号。
这让编译器感到困惑(它似乎试图将您的构造函数定义解析为 foo
类型的对象的名称)。
你知道 C++ 不是 Java!
关于c++ - 变量的多重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38973534/