【发布时间】:2021-06-26 01:34:49
【问题描述】:
我正在尝试定义一个类模板和一个运算符重载:
template<class T>
class complex{
public:
T x,y;
complex(T a, T b): x(a), y(b) {}
complex<T> operator+ (const complex<T>& c){
complex<T> s{x+c.x, y+c.y};
return s;
}
};
int main(){
complex<int> c1{1,2};
complex<int> c2{3,4};
complex<int> c3 = c1 + c2;
cout << "x: " << c3.x << " y: " << c3.y << endl;
}
这很好用,但是如果我将 operator+ 重载的定义更改为:
complex<T> operator+ (const complex<T>& c){
complex<T> s;
s.x = x + c.x;
s.y = y + c.y;
return s;
}
它报告编译错误:
error: no matching constructor for initialization of 'complex<int>'
complex<T> s;
^
那么为什么第二个定义不起作用?
【问题讨论】:
-
complex<T> s;-- 仔细查看你的代码。然后问问自己你将如何构建一个没有参数的complex<T>。真正令人惊讶的是,您使用了模板等半高级主题,却没有看到没有默认构造函数的基本错误。 -
顺便说一句,您甚至不需要引入
s变量,即使在有效的代码中:return {x+c.x, y+c.y};
标签: c++ templates operator-overloading