C++中的“未定义符号”错误
我昨天发布了这个。人们建议我应该有Point.h
和Point.cpp
文件,因为我使用的是template
。我为我的课程Point
创建了单独的文件,但仍然收到错误消息。C++中的“未定义符号”错误
//Point.h
Point(T = 0, T = 0, string = "Deafault Point");
~Point();
T operator-(const Point<T> &);
//Point.cpp
template < typename T >
Point<T>::Point(T x,T y, string name)
:X(x), Y(y), Name(name)
{
}
template < typename T >
Point<T>::~Point()
{
}
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.cpp
#include <iostream>
#include <math.h>
#include "Point.h"
using namespace std;
int main() {
Point<double> P1(3.0, 4.1, "Point 1");
cout << P1;
Point<double> P2(6.4, 2.9, "Point 2");
cout << P2;
cout << (P2 - P1);
return EXIT_SUCCESS;
}
这是我得到:
Undefined symbols:
"std::basic_ostream<char, std::char_traits<char> >& operator<< <double (std::basic_ostream<char, std::char_traits<char> >&, Point<double> const&)", referenced from:
_main in main.o
_main in main.o
"Point<double>::operator-(Point<double> const&)", referenced from:
_main in main.o
"Point<double>::Point(double, double, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)", referenced from:
_main in main.o
_main in main.o
"Point<double>::~Point()", referenced from:
_main in main.o
_main in main.o
_main in main.o
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
任何帮助表示赞赏...
人建议我应该有Point.h和Point.cpp文件,因为我m使用模板
无论谁提出这是错误的。模板的实现必须可见。
你可以分开执行到一个文件,但你需要包括它以及之后。当你可以隐藏模板的实现时,唯一的情况是当你知道特殊化并且事先声明它们时。 (这并不适用于此)
您需要为模板单个文件:
//Point.h
template <typename T>
struct Point
{
Point(T = 0, T = 0, string = "Deafault Point");
~Point();
T operator-(const Point<T> &);
};
template < typename T >
Point<T>::Point(T x,T y, string name)
:X(x), Y(y), Name(name)
{
}
template < typename T >
Point<T>::~Point()
{
}
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));;
}
而且,在头裸string
建议您在标题中有一个using namespace std;
为好。这是不好的做法,请删除using
指令并限定名称std::string
。
它的工作!谢谢:) – 2012-07-25 01:43:46
有关模板类的所有已定义和已实现的代码应该写入'.h'文件,否则将会出现编译错误。
不完全正确。实现需要可见,但不一定在'.h'文件中。即使这样,如果你事先知道所有的专业化。 – 2012-07-25 01:29:29
您用于构建可执行文件的确切命令是什么? – YePhIcK 2012-07-25 01:24:09
你发布的代码甚至都不是很正确。也许阅读一本关于C++的好书介绍? – 2012-07-25 01:25:04
仅供参考您的'operator-'不是强制返回类型T.'sqrt()'总是返回一个double。不一定是编译错误之一,但如果你做了一个'Point' –
Russ
2012-07-25 01:29:46