简体   繁体   English

带有运算符重载的类模板

[英]class template with operator overloading

I'm trying to define a class template and an operator overloading:我正在尝试定义一个类模板和一个运算符重载:

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;
}

This works fine, but if I change the definition of operator+ overloading to:这工作正常,但如果我将 operator+ 重载的定义更改为:

    complex<T> operator+ (const complex<T>& c){
        complex<T> s;
        s.x = x + c.x;
        s.y = y + c.y;
        return s;
    }

it reports a compilation error:它报告编译错误:

error: no matching constructor for initialization of 'complex<int>'  
       complex<T> s;  
                  ^

So why doesn't the second definition work?那么为什么第二个定义不起作用呢?

complex<T> s;

This attempts to default-construct an instance of complex<T> .这会尝试默认构造complex<T>的实例。

The problem with that is there is no default constructor for this instantiated template class.问题是这个实例化的模板类没有默认构造函数。 The only constructor you defined in your template requires two parameters, and they are completely absent here.您在模板中定义的唯一构造函数需要两个参数,此处完全不存在。

You can add some reasonable, default constructor (a constructor that takes no parameters) to your template:您可以向模板添加一些合理的默认构造函数(一个不带参数的构造函数):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM