2012-07-24 132 views
1

我有Point類,它有X,YName作爲數據成員。我重載C++中的「未定義符號」錯誤

T operator-(const Point<T> &); 

這種計算兩個點之間的距離,並返回一個值

template < typename T> 
T Point<T>::operator-(const Point<T> &rhs) 
{ 
cout << "\nThe distance between " << getName() << " and " 
<< rhs.getName() << " = "; 

return sqrt(pow(rhs.getX() - getX(), 2) + pow(rhs.getY() - getY(), 2));; 
} 

main功能

int main() { 

Point<double> P1(3.0, 4.1, "Point 1"); 

Point<double> P2(6.4, 2.9, "Point 2"); 

cout << P2 - P1; 
return EXIT_SUCCESS; 
} 

但問題是,這個程序不編譯,我收到此錯誤:

Undefined symbols: 
"Point<double>::operator-(Point<double>&)", referenced from: 
    _main in main.o 
ld: symbol(s) not found 
collect2: ld returned 1 exit status 

任何幫助表示讚賞...

+1

你有沒有包括運營商的標頭中的實現,或在.cpp文件? – juanchopanza 2012-07-24 10:25:51

+0

@juanchopanza是的。我只有一個.cpp文件,它具有實現。 – 2012-07-24 10:31:08

+0

看到我的回答下面 – 2012-07-24 10:34:07

回答

2

您不能編譯非專門的模板。您必須將定義代碼放在標題中。

+0

模板不能作爲翻譯單位的一部分自行編譯。你需要一個實例化或專業化來編譯它們。 – nurettin 2012-07-24 10:31:57

+0

重複:http://stackoverflow.com/questions/999358/undefined-symbols-linker-error-with-simple-template-class?rq=1 可能的重複項: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file http://stackoverflow.com/questions/3749099/why-should-the-implementation-and-the-declaration-of-a -template-class-in-the-lq = 1 – nurettin 2012-07-24 11:00:10

+0

我把定義放在.h文件中,我仍然收到相同的錯誤! – 2012-07-24 11:50:22

0

您需要將您的Point模板類放在.hpp文件中,並在每次使用Point時包含該模板類。

+0

我把定義放在.h文件中,我仍然收到相同的錯誤! – 2012-07-24 11:50:51

0

您必須在每個使用它們的文件中包含模板,否則編譯器無法爲您的特定類型生成代碼。

運算符之間也有一個優先級,當它們超載時它們不會被改變。您的代碼將被視爲

(cout << P2) - P1; 

試試這個

cout << (P2 - P1);