【发布时间】:2021-01-17 09:29:06
【问题描述】:
我已经定义了一个类模板MyVector 并重载了operator<< 以打印它所包含的向量。
//MyVector definition
template<int n, typename T>
class MyVector{
private:
vector<T> vetor;
public:
//Several Methods
MyVector operator+(MyVector& v){
//Adds 2 vectors
}
template<typename U, int m>
friend ostream& operator << (ostream& o, MyVector<m,U>& v);
};
template<typename T, int n>
ostream& operator << (ostream& o, MyVector<n,T> &v){
o << "[";
for(auto itr = v.vetor.begin(); itr != v.vetor.end()-1; ++itr){
o << *itr <<", ";
}
o << v.vetor.back() << "]";
return o;
}
对于简单的用例,该运算符似乎可以正常工作,但是当添加 2 个 MyVector 实例时,operator<< 会抛出:
invalid operands to binary expression
int main(){
MyVector<2,int> v1;
MyVector<2,int> v2;
MyVector<2,int> v3;
v1.add(1,2);
v2.add(3,4);
v3 = v1+v2;
cout << v3 << endl; // --> This prints "[7,11]" to the console
cout << v1+v2 << endl; // --> This throws the exception
}
我在这里错过了什么?
【问题讨论】:
-
只有当您打算修改参数时,才应将参数作为左值引用传递。在任何其他情况下,通过值或 const 引用传递(以避免昂贵的复制)
标签: c++ operator-overloading operator-keyword