【发布时间】:2015-03-07 05:13:47
【问题描述】:
我编写了这段代码
声明:
template <class T>
class Matrix
{
std::vector< std::vector<T> > mat;
size_t rows , cols;
public:
Matrix<T>();
Matrix<T>(const std::string);
Matrix(const size_t r, const size_t c, const std::vector<T> v);
Matrix<T> operator=(const Matrix<T> &other);
friend std::ostream& operator<<(std::ostream &os , Matrix<T> m);
};
功能:
template <class T>
std::ostream& operator<<(std::ostream &os , Matrix<T> m){
for (size_t i = 0; i < m.rows; i++)
{
for (size_t j = 0; j < m.cols; j++)
{
os << m.mat[i][j] << " ";
}
os << std::endl;
}
return os;
}
主要:
int main(){
std::vector<int> v(9);
v[0] = 1;
v[1] = 2;
v[2] = 3;
v[3] = 4;
v[4] = 5;
v[5] = 6;
v[6] = 7;
v[7] = 8;
v[8] = 9;
Matrix<int> m = Matrix<int>(2, 3, v);
std::cout << m;
}
我收到此错误:
错误 1 错误 LNK2019:无法解析的外部符号“类 std::basic_ostream > & __cdecl 运算符
&,类矩阵)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$Matrix@H@@@Z) 在函数 _main C:\Users\igor\documents\visual studio 中引用 2013\Projects\matrix\matrix\Source.obj 矩阵
我尝试在没有朋友的情况下编写它,但出现了不同的错误。
我做错了什么?
【问题讨论】:
-
在
main.cpp中的#included 是.h 文件中的定义吗?发布MCVE 将非常有用。 -
我不知道这是否与您的问题有关(我认为不是),但您仍然应该让您的函数采用
const Matrix<T>&而不是Matrix<T> -
@IgorGumush 直接在头文件中定义模板化运算符,而不是在 .cpp 文件中
-
由于这是一个模板,
operator<<的定义必须是#included 和标题。这是你做的吗?
标签: c++ matrix operator-overloading