【发布时间】: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;
}
【问题讨论】:
-
与您的问题无关,但使用the generally bad
using namespace std;,那么您应该考虑不将您的类命名为与the standardstd::complexclass template 相同。 -
至于你的问题,如果我们看
+运算符的用法,假设我们有(更简单的)C3 = C1 + C2,那么它与C3 = C1.operator+(C2)相同。这对你有帮助吗?
标签: c++ constructor operator-overloading overloading