C++复数重载的一个小问题,就是有一点点迷糊
/*****************************************************
*声明复数的类,complex,使用友元函数add实现复数加法。
*版本:2013-08-25-V1.0 复数类Complex 定义
*编写人:zhengkailun
*****************************************************/
//复数类的定义
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex{
public:
Complex(){};//默认构造函数
Complex(double Real,double Imagine);//重载构造函数
Complex(const Complex& rhs){}//copy构造函数
Complex& operator =(const Complex& rhs){}//赋值操作符
~Complex(){} //析构函数
double get_Real(); //获得实部
double get_Imagine();//获得虚部
friend Complex& operator +(const Complex& lhs,const Complex& rhs); //重载复数加法函数友元函数
private:
double real,imagine; //虚数的实部虚部声明
};
#endif//COMPLEX_H
/*****************************************************
*Complex类的实现文件
*编写人:zhengkailun
*****************************************************/
#include"Complex.h"
#include<iostream>
Complex::Complex(double Real,double Imagine)
{
real = Real;
imagine = Imagine;
}
double Complex::get_Real()
{
return real;
}
double Complex::get_Imagine()
{
return imagine;
}
Complex& operator +(const Complex& lhs,const Complex& rhs) //重载复数加法函数友元函数
{
//return Complex(lhs.real + rhs.real,lhs.imagine + rhs.imagine);
Complex com_sum(0,0);
com_sum.real = lhs.real + rhs.real;
com_sum.real = lhs.imagine + rhs.imagine;
std::cout<<com_sum.real; //这里会输出 9
return com_sum; //我认为这里是个局部量,在花括号后面就被析构,所以重载的+操作符返回的是一个随机值。
}
/*************************************************
*复数类测试函数
*版本:2013—06-25-V1.0
*编写人:zhengkailun
*************************************************/
#include<iostream>
#include"Complex.h"
int main()
{
Complex com_one(5,4),com_two(5,5);
std::cout<<com_one.get_Real()<<" "<<com_one.get_Imagine();
std::cout<<"The complex com_one and the com_two 's sum is "
<<(com_one+com_two).get_Real(); //这里输出-9.2596e+061
return 0;
}