gpt4 book ai didi

C++ 链接器错误,未解析的外部

转载 作者:行者123 更新时间:2023-11-28 06:15:51 26 4
gpt4 key购买 nike

为什么我在尝试编译这段代码时遇到链接器错误,这基本上是一个复杂的模板类矩阵的代码,矩阵是一个方阵,所以如果输入大小“3”,它意味着 [3] 的矩阵][3] 但不知何故它给了我错误,有什么帮助吗?

#include <iostream>
#include <iomanip>
using namespace std;

template <class T>
class matrix
{
private:
T** real;
T** imag;
int size;
public:
matrix(int = 0);
friend ostream& operator<<(ostream& out, matrix<T>);
};

// constructor

template <class T>
matrix<T>::matrix(int length)
{
size = length;

real = new T*[size];
for (int i = 0; i < size; i++)
real[i] = new T[size];

imag = new T*[size];
for (int i = 0; i < size; i++)
imag[i] = new T[size];

cout << "Enter real elements of matrix: ";
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
cin >> real[i][j];

cout << "Enter imag elements of matrix: ";
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
cin >> imag[i][j];
}

// functions defined here

template <class T>
ostream& operator<<(ostream& out, matrix<T> arg)
{
out << showpos;
for (int i = 0; i < arg.size; i++)
for (int j = 0; j < arg.size; j++)
out << arg.real[i][j] << arg.imag[i][j] << " ";
out << endl;
return out;
}

int main()
{
matrix <int> obj1(3);
cout << obj1;
}

最佳答案

因为编译器需要非模板函数。

friend ostream& operator<<(ostream& out, matrix<T>);

但是你定义为

template <class T>
ostream& operator<<(ostream& out, matrix<T> arg)
{
//some code
}

修改类定义为

template<class N> friend ostream& operator<<(ostream& out, matrix<T>);

Here是指向 template friend operators 的链接,它提供了有关使用模板 friends 的很好的解释。

编辑 1:

根据 vsoftco 的建议,您还可以使用替代方法来定义类内:

class matrix{
//some code

//we don't need template here
friend ostream& operator<<(ostream& out, matrix<T>)
{
out << showpos;
for (int i = 0; i < arg.size; i++)
for (int j = 0; j < arg.size; j++)
out << arg.real[i][j] << arg.imag[i][j] << " ";
out << endl;
return out;
}
};

关于C++ 链接器错误,未解析的外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30337989/

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