【发布时间】:2016-01-31 16:43:24
【问题描述】:
我试图将一个对象作为重载 operator+ 的参数传递(并且该类是一个模板类),但它给了我一个错误,其中指出:
error C2955: 'Kvader': use of class template requires template argument list
这是我的课:
template <class Q>
class Kvader {
private:
Q a, b, c;
public:
Kvader(const Kvader &temp);
Kvader operator+(Kvader);
};
这是我的重载+方法:
template <class Q>
Kvader Kvader<Q>::operator+(Kvader<int> temp) {
a += temp.a;
b += temp.b;
c += temp.c;
return *this;
}
我以为
Kvader Kvader<Q>::operator+(Kvader<int> temp)
作为参数列表就足够了。我做错了什么?
在我的 main 中,我只创建了 2 个对象(第二个调用了复制构造函数),然后我尝试将它们添加在一起。
int main(){
Kvader<int> object1, object2(object1);
object1 = object1 + object2;
return 0;
}
【问题讨论】:
-
返回类型中需要一个模板参数。作为猜测,
Kvader<Q> Kvader<Q>::operator+(Kvader<int> temp) ... -
operator+中的参数应该是const&并且它的返回类型应该是这样的引用:Kvader<Q>& Kvader<Q>::operator+(const Kvader<Q>& temp)。此外,您还可以混合专业化(针对ints)和定义模板。 -
@Patryk
operator +=应该返回一个引用,而不是operator +。 -
@JemCpp 对不起我的错误我错过了那个细节。确实应该是
Kvader<Q> Kvader<Q>::operator+(const Kvader<Q>& temp)
标签: c++ operator-overloading class-template