【问题标题】:Additon of complex numbers using operator overloading in c++使用 C++ 中的运算符重载添加复数
【发布时间】:2017-11-11 05:17:03
【问题描述】:

无法理解下面给定程序中的代码块。 特别是变量 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;


}

【问题讨论】:

标签: c++ constructor operator-overloading overloading


【解决方案1】:
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;

【讨论】:

  • 你错过了一个非常重要的部分...C1 呢?
  • @madhurachanna,在运算符中,宿主类是第一个操作数 (C1),第二个类是运算符的参数 (C2)。
  • 但我听说我们不需要给 C1,因为它是隐含的.. 执行后我得到了所需的答案......
  • 你不需要写C1.operator+(C2)C1+C2 完全等价于它。
猜你喜欢
  • 2020-12-13
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 1970-01-01
相关资源
最近更新 更多