【问题标题】:Redefinition in C++, previous definition in header file?C ++中的重新定义,头文件中的先前定义?
【发布时间】:2023-03-29 16:47:01
【问题描述】:

所以我很困惑。尝试实现先前在头文件中声明的方法时出现重新定义错误。我在标题中添加了包含防护,但仍然出现相同的错误。如果有人可以向我解释我没有看到什么,那就太好了。

在 main.cpp:2 包含的文件中: ./thing.cpp:7:12:错误:重新定义“方法” 整数事物::方法(无效) ^ ./thing.hpp:12:6: 注意:之前的定义在这里 整数方法(无效){}; ^

--编辑--

我现在得到以下信息:

重复符号 __ZN5Thing6methodEv 在: 主要的.o thing.o ld:架构 x86_64 的 1 个重复符号

thing.hpp:

#ifndef THING_H
#define THING_H

class Thing {

public:
        int a;
        int b;
        char c;

        int method(void) {};
        Thing(int anA, int aB, char aC): a(anA), b(aB), c(aC) {};


};

#endif

thing.cpp

#include <iostream>
#include <stdio.h>
#include "thing.hpp"

using namespace std;

int Thing::method(void)
{
        return 5;

}

ma​​in.cpp

#include <iostream>
#include "thing.cpp"

using namespace std;

Thing* thing = new Thing(5,5,'c');

int main(int argc, char ** argv)
{
        cout << thing->method() <<endl;

}

【问题讨论】:

  • 为什么在 main.cpp 中包含 thing.cpp

标签: c++ header include guard redefinition


【解决方案1】:

在你的头文件中你有:

int method(void) {};

这是一个内联定义,而不是一个声明。 {} 实际上是向编译器提供(尽管是空的)函数体。如果要在另一个文件中定义函数,请删除 {}

此外,您的main.cpp 文件顶部有#include "thing.cpp" 而不是#include "thing.hpp"

【讨论】:

    【解决方案2】:

    在 main.cpp 中你需要改变:

    #include "thing.cpp"
    

    到:

    #include "thing.hpp"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2011-02-13
      相关资源
      最近更新 更多