首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++复数重载的一个小疑点,就是有一点点迷糊

2013-09-06 
C++复数重载的一个小问题,就是有一点点迷糊/***************************************************** *声

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



主要是在重载友元函数的返回值哪里出错,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;   //我认为这里是个局部量,在花括号后面就被析构,所以重载的+操作符返回的是一个随机值。-9.2596e+061
       而代码优化成return Complex(lhs.real + rhs.real,lhs.imagine + rhs.imagine);结果就不会出问题,我认为是析构函数的问题,请给我讲讲两种方法的差异,如果用那种返回com—sum的对象的方法能不能实现。 c++ 对象 用友
[解决办法]
返回值类型错误。编译器没提出警告么?

iostream的cout是先用个链表缓冲你输,碰到endl的时候再喷出去。

我不确定是直接value copy还是cache 引用,这个你要自己去看看代码。如果是cache引用,应该就是你出现的这种情况。另外你的assign重载也没贴代码,main函数里的内容,我就没仔细看。
[解决办法]
operator+ 按照语义来说,两个参数都是不应该改变的,所以只能返回一个对象,你的函数返回值是引用,错误。
反过来的例子 operator+=就是在原来的值上面加一个值,函数的返回值应该是引用。

既然return一个临时对象,显然函数的返回值应该是对象。

另外一对例子就是前++和后++。
前++返回引用,后++只能返回对象。

热点排行