2017-11-11 144 views
1

無法理解下面給定程序中的一段代碼。 特別是變量,具有返回類型作爲複雜(類名稱),當我們返回變量,臨時返回到哪裏的溫度? 這就是程序中的return(temp);使用C++中的運算符重載的複數的增加

方案

#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; 


} 
+0

無關您的問題

C5=C1.operator+(C2) 

,但與[普遍不好'使用命名空間std; '](HTT ps://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)那麼你應該考慮*不*命名您的類相同[標準的'std :: complex 'class template](http://en.cppreference.com/w/cpp/numeric/complex)。 –

+0

至於你的問題,如果我們看看'+'操作符的用法,可以說我們有(更簡單的)'C3 = C1 + C2',那麼就和'C3 = C1.operator +(C2) '。這對你有幫助嗎? –

回答

0
complex C5; 
C5=C1+C2; 

意味着相當於

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

你錯過了一個非常重要的部分...... C1在哪裏? –

+0

@Someprogrammerdude,這是非常重要的一點。 – Arash

+0

C1? dint get ... –