【问题标题】:class template with operator overloading具有运算符重载的类模板
【发布时间】: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&lt;T&gt; s; -- 仔细查看你的代码。然后问问自己你将如何构建一个没有参数的complex&lt;T&gt;。真正令人惊讶的是,您使用了模板等半高级主题,却没有看到没有默认构造函数的基本错误。
  • 顺便说一句,您甚至不需要引入 s 变量,即使在有效的代码中:return {x+c.x, y+c.y};

标签: c++ templates operator-overloading


【解决方案1】:
complex<T> s;

这会尝试默认构造complex&lt;T&gt; 的实例。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    相关资源
    最近更新 更多