gpt4 book ai didi

c++ - C++ 中的 “Undefined symbols” 错误

转载 作者:行者123 更新时间:2023-11-30 00:38:08 24 4
gpt4 key购买 nike

我昨天发布了这个。人们建议我应该有 Point.hPoint.cpp 文件,因为我正在使用 template。我为我的类 Point 创建了单独的文件,但我仍然收到错误。

//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

感谢任何帮助...

最佳答案

People suggested that I should have Point.h and Point.cpp files since I'm using template

无论是谁提出的,都是大错特错。模板的实现必须可见。

您可以将实现分离到一个文件中,但之后您还需要包含它。唯一可以隐藏模板实现的情况是您知道特化并事先声明它们。 (这里不适用)

模板需要一个文件:

//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));;
}

此外, header 中的裸露 string 表明您在 header 中也有一个 using namespace std;。这是不好的做法,删除 using 指令并限定名称 std::string

关于c++ - C++ 中的 “Undefined symbols” 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com