重载遇到的问题

寒沙胜雪 寒沙胜雪 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
complex.h的

#if ! defined(COMPLEX_H_)
#define COMPLEX_H_

class complex
{
///Attributes:
private:
double real;
double image;
double radius;
double angle;
///Operations:
public:
complex(double real = 0, double image = 0);
complex(const complex &c);
~complex(){};
void setvalue(double real, double image);
double getreal(){return real;}
double getimage(){return image;}
double getradius(){return radius;}
double getangle(){return angle;}
complex operator +(complex comp);
complex operator *(complex comp);
complex operator !();
operator double();
};


#endif




complex.cpp

#include "complex.h"
#include <iostream>
#include <cmath>
using std::cout;
using std::endl;

complex::complex(double real, double image)
{
cout << "Construct Function!" << endl;
setvalue(real, image);
}

complex::complex(const complex &c)
{
cout << "Copy Construct Function!" << endl;
setvalue(c.real, c.image);
}

void complex::setvalue(double real, double image)
{
this->real = real;
this->image = image;
this->radius = sqrt(real * real + image * image);
this->angle = atan2(image, real);
}

complex complex::operator +(complex comp)
{
cout << "+ override function" << endl;
return complex(this->real + comp.real, this->image + comp.image);
}
complex complex::operator *(complex comp)
{
///(a+bi)(c+di) = ac + (ad+bc)i - bd = ac - bd + (ad+bc)i
return complex(this->real * comp.real - this->image * comp.image,
this->real * comp.image + this->image * comp.real);
}
///重载!求复数的共轭复数
complex complex::operator !()
{
return complex(this->real, -this->image);
}
///重载double()求复数的模
complex::operator double()
{
return fabs(radius);
}


main.cpp

#include <iostream>
#include "complex.h"
using std::cin;
using std::cout;
using std::endl;

int main(void )
{
double real1,image1,real2,image2;

cout << "Please the first complex:" << endl;
cin >> real1 >> image1;
cout << "Please the second complex:" << endl;
cin >> real2 >> image2;
complex comp1(real1, image1);
complex comp2(real2, image2);
cout << (comp1+comp2).getreal() << endl;
return 0;
}


不用看完整的类定义,只需要看下重载的+那个函数定义即可,我在main中只用了+做试验,但是用了之后,发现在gcc(code::blocks)下输出这种结果


Please the first complex:
1.1 2.2
Please the second complex:
3.3 4.4
Construct Function!
Construct Function!
Copy Construct Function!
+ override function
Construct Function!
4.4


我明白最后出现Construct Function!是用了RVO(Return Value Optimization),但是在调用重载+函数之前为何会有一个Copy Construct Function!
这是什么原因呢?它拷贝构造的谁呢?
还有一个问题,那就是拷贝构造函数如果在参数中不加const,运行结果会不对,原因是重载了double,但是我在拷贝构造函数里面也没有改变参数的值,为何会有区别呢?

以上两个问题,已困扰多日,希大侠帮忙解决下,谢谢了。
...全文

相关推荐

评论 12
收藏 已收藏
分享
返回顶部
寒沙胜雪
C++ 语言 65,214 成员 250,514 内容