使用c ++中的运算符重载添加复数

时间:2017-11-11 05:17:03

标签: c++ constructor operator-overloading overloading

无法理解下面给定程序中的代码块。 特别是变量,temp有返回类型作为复合体(类名),当我们返回变量时,temp返回到哪里? 这是程序中的return(temp);

该计划

#include <iostream>
using namespace std;
class complex
{
public:
    complex();//default constructors
    complex(float real, float imag)//constructor for setting values
    {
        x = real;
        y = imag;
    }
    complex operator +(complex);
    void display(void);
    ~complex();

private:
    float x;
    float y;

};

complex::complex()
{
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
complex complex::operator+(complex c)
{
    complex temp;
    temp.x = x + c.x;
    temp.y = y + c.y;
    return(temp);
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
void complex::display(void) {
    cout << x << "+j" << y << "/n";

}

complex::~complex()
{
}


int main()
{
    complex C1, C2, C3,C4;
    C1 = complex(1, 3.5);//setting of first number
    C2 = complex(2,2.7);//setting of second number
    C4 = complex(2, 5);

    C3 = C1 + C2+C4;//operator overloading
    cout << "C1 = ";
    C1.display();
    cout << "\n C2 = ";
    C2.display();
    cout << "\n C4 = ";
    C4.display();
    cout << "\n C3 = ";
    C3.display();

    system("pause");

    return 0;


}

1 个答案:

答案 0 :(得分:0)

complex C5;
C5=C1+C2;

装置

C5=C1.operator+(C2)

相当于

complex temp;
temp.x = x + C2.x; /* x=C1.x*/
temp.y = y + C2.y; /* y=C1.y*/
C5=temp;