class 具有运算符重载的模板

class template with operator overloading

我正在尝试定义一个 class 模板和一个运算符重载:

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> 的实例。

问题是这个实例化模板没有默认构造函数class。您在模板中定义的唯一构造函数需要两个参数,而它们在这里完全没有。

您可以向模板添加一些合理的默认构造函数(不带参数的构造函数):

complex(): x(0), y(0) {}