c++ - 变量的多重定义

标签 c++

这是我的代码:

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/

相关文章:

C++ 为什么这种方式很危险?

c++ - std::future 如何影响关联的 std::packaged_task 的生命周期?

c++ - 显示QList内容

c++ - VkLayer_param_checker.dll 访问冲突

c++ - 错误 C1190 : managed targeted code requires a '/clr' option

c++ - 如何在 Visual Studio 中禁用从父级继承的特定警告?

c++ - 在多线程环境中使用 CList

c++ - 使用 pthread 时的随机结果

c++ - 为什么我们通过了链接阶段仍然错过了符号?

c++ - cmake 找到 opencv 库的路径,但 make 没有找到 opencv 函数 Rodrigues