【问题标题】:Undefined reference while including header in C++在 C++ 中包含标头时未定义的引用
【发布时间】:2011-06-05 16:05:18
【问题描述】:

当我决定将其拆分为文件时,我正在处理我的项目。但是我遇到了这样的问题,我通过谷歌找到的所有建议都是关于忘记链接我做对的两个目标文件(至少我认为是这样)。

生成文件:

test : class.o main.o
 g++ class.o main.o -o test.exe

main.o : main.cpp
 g++ main.cpp -c

class.o : class.cpp
 g++ class.cpp -c

ma​​in.cpp

#include <iostream>
#include "class.h"
using namespace std;

int main() {
 Trida * t = new Trida(4);
 t->fce();
 return 0;
}

class.h

#ifndef CLASS
#define CLASS
class Trida {
private:
 int a; 
public:
 Trida(int n); 
 void fce();
};
#endif

class.cpp

#include <iostream>

using namespace std;

class Trida {
private:
 int a;

public:
 Trida(int n) {
  this->a = n;
 } 

 void fce() {
  cout << this->a << endl;
 }
};

错误信息:

gwynbleidd@gwynbleidd-pc:~/Skola/test$ make
g++ class.cpp -c
g++ main.cpp -c
g++ class.o main.o -o test.exe
main.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Trida::Trida(int)'
main.cpp:(.text+0x54): undefined reference to `Trida::fce()'
collect2: ld returned 1 exit status
make: *** [test] Error 1

【问题讨论】:

    标签: c++ header include undefined-reference


    【解决方案1】:

    所以这就是你做错了什么。在 class.cpp 中,您重新创建了一个 new Trida 类,而不是实现您在 class.h 中创建的类。你的 class.cpp 应该看起来更像这样:

    #include <iostream>
    #include "class.h"
    
    using namespace std;
    
    Trida::Trida(int n)
    {
      this->a = n;
    }
    
    void Trida::fce() { cout << this->a << endl; }
    

    实际上你应该在构造函数中使用初始化而不是赋值:

    Trida::Trida(int n) : a(n) {}
    

    【讨论】:

    • 哇,真快。问题比我想象的要简单。非常感谢:-)
    【解决方案2】:

    您定义类trida 两次(在头文件class.h 和源文件class.cpp 中) 你的 class.cpp 文件应该是这样的

    #include <iostream>
    #include "class.h" //include "class.h"
    using namespace std;
    
    Trida::Trida(int n):a(n) //Initialization list
    {
    } 
    
    void Trida::fce()
    {
      cout << this->a << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多