2011-01-08 28 views
0

我正在處理我的項目,而我決定將其分解爲文件。然而,我遇到了像這樣的問題,我通過谷歌發現的所有建議都是關於忘記連接兩個對象文件,我正在做對(至少我是這麼認爲的)。在C++中包含標題時未定義的引用

生成文件:

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 

的main.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; 
} 
}; 

錯誤消息:

[email protected]:~/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 

回答

4

因此,這裏是你做錯了什麼。在class.cpp中,您重新創建了一個新的 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) {} 
+0

哇,這是快。問題比我想象的要簡單。非常感謝你 :-) – Gwynbleidd 2011-01-08 05:28:18

0

你定義在頭文件類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; 
} 
相關問題