【发布时间】:2014-11-13 21:49:14
【问题描述】:
在我的课堂上:
#ifndef __MYVECTOR_CLASS__
#define __MYVECTOR_CLASS__
template<class Type>
class MyVector{
....
MyVector& operator=(const MyVector& source); //works
friend MyVector<Type> operator+(MyVector<Type> lhs, const MyVector<Type> &rhs); //doesnt
....
};
template<class Type>
MyVector<Type>& MyVector<Type>::operator=(const MyVector &v){
if (_d != v._d){
_d = v._d;
_deleteArray();
_createArray(_d);
}
_assignValues(v._vector, (v._vector + _d));
return *this;
};
template<class Type>
MyVector<Type> operator+(MyVector<Type> lhs, const MyVector<Type> &rhs){
if (lhs._d == rhs._d){
for (int index = 0; index < lhs._d; index++){
lhs._vector[index] += rhs._vector[index];
}
}
return lhs;
};
#endif // __MYVECTOR_CLASS__
没有包括其他非运算符函数,因为它们都可以正常工作。 不知道为什么它不起作用。
在源文件中:
int main(){
MyVector<float> a(10);
MyVector<float> b(10);
a = b; // works alone
a = a + b; //breaks
return 0;
}
还有错误:
错误 1 错误 LNK2001:未解析的外部符号“类 MyVector __cdecl operator+(class MyVector,class MyVector)"
Error 2 error LNK1120: 1 unresolved externals
已编辑:
添加了构造函数。
template<class Type>
MyVector<Type>::MyVector(int size){
_d = size;
_createArray(_d);
_assignValues(0);
}
【问题讨论】:
-
这可能是一个愚蠢的问题,但您是否包含了包含该类的头文件或者它是主源文件的一部分?
-
我想你有
MyVector的复制构造函数? -
另外,您应该使用
const MyVector<Type>& lhs,作为左侧值。 -
我包含了标题类。是的,我现在添加它。为什么我应该使用 const Im 复制对象并向其添加值。
-
是的,我其他一切都很好。只有算术运算符没有。
标签: c++ class templates math class-template