首页 > 解决方案 > 错误:没有匹配的函数调用'Complex::Complex()'

问题描述

我刚从函数重载开始,我被以下代码困住了:

#include<iostream> 
using namespace std; 

class Complex
{
double real; 
double img; 

public: 
    Complex(double r, double i)
    {
        real = r; 
        img = i; 
    }
    
    void display()
    {
        cout<<real<<" + i"<<img<<endl; 
    }
    
    Complex operator+(Complex c)
    {
        Complex temp; 
        temp.real = real + c.real; 
        temp.img = img + c.img; 
        return temp;
    }
    
    Complex operator-(Complex c)
    {
        Complex temp; 
        temp.real = real - c.real; 
        temp.img = img - c.img; 
        return temp;
    }
    }; 

    int main()
    {
    Complex c1(23.89, -42.98), c2(54.23, 53.35); 

    cout<<"Adding the two complex numbers: "<<endl;
    Complex c3 = c1 + c2; 
    c3.display();

    cout<<"Subtracting two complex numbers: "<<endl; 
    Complex c4 = c1 - c2; 
    c4.display();

    return 0;
    }

两个运算符重载函数的错误是:

没有匹配函数调用“Complex::Complex()”复杂温度;^~~~

标签: c++operator-overloading

解决方案


And indeed there is no Complex::Complex().

In this code

    Complex temp; 
    temp.real = real + c.real; 
    temp.img = img + c.img;
    return temp;

how do you think temp is being constructed? The compiler is looking for Complex::Complex() and when it doesn't find it that's an error.

You could add Complex::Complex() but the simpler fix is to use the constructor you have already written

    Complex temp(real + c.real, img + c.img);
    return temp;

Or even simpler, get rid of temp completely

    return Complex(real + c.real, img + c.img);

推荐阅读