2012-07-24 133 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);