c++类成员函数定义方法与运算符重载(2)

这个例子虽代码繁杂,但却蕴含很多东西

1.里面蕴含构造函数的调用时机
  • 1.已有的对象初始化一个新定义的对象
  • 2.当对象作为函数的实参传递给函数的形参时(例子中有体现)
  • 3.当函数的返回值是类的对象,函数执行返回时
Complex Complex::sub(Complex c)
{
	return Complex(real-c.real,image-c.image);
}

return返回的是一个无名函数,但是在return结束后是调用了一个拷贝构造函数,这与局部变量在函数结束时释放一点也不矛盾,这里指的是3

2.给对象赋值的两种方式

Complex a(1.8,-2.4),b(4.3,4.7);
Complex c=a.add(b); //给对象赋初值的又一方式

3.this指针
Complex Complex::operator+(Complex c) 
{	//this 指针 
	Complex z(real+c.real,image+c.image);
	return(z);//此时间点,系统自动调用复制构造函数 
}

这里其实可以改写为
Complex z(this->real+c.real,this->image+c.image);
谁调用它this指针便指向谁

4.运算符重载
//加法 运算符重载函数
Complex Complex::operator+(Complex c) 
{	//this 指针 
	Complex z(real+c.real,image+c.image);
	return(z);//此时间点,系统自动调用复制构造函数 
}

代码如下

#include<iostream>
using namespace std;
class Complex
{
private:
	double real,image;
public:
	Complex(double px=0,double py=0)
	{
		real=px;
		image=py;
	}
	Complex add(Complex c);
	Complex sub(Complex c);
	//operator+是函数名,实现 加法 运算符重载
	Complex operator+(Complex c); 
	Complex operator-(Complex n); 
	void print();
}; 
Complex Complex::add(Complex c)
{
	//return Complex(real+c.real,image+c.image);
	//改写成易懂形式 
	Complex z(real+c.real,image+c.image);
	return(z);//此时间点,系统自动调用复制构造函数 
}
Complex Complex::sub(Complex c)
{
	return Complex(real-c.real,image-c.image);
}
void Complex::print()
{
	if(image<0.0)
		cout<<"("<<real<<image<<"i"<<")"<<endl;
	else 
		cout<<"("<<real<<"+"<<image<<"i"<<")"<<endl;	
}
//加法 运算符重载函数
Complex Complex::operator+(Complex c) 
{	//this 指针 
	Complex z(real+c.real,image+c.image);
	return(z);//此时间点,系统自动调用复制构造函数 
}
Complex Complex::operator-(Complex n) 
{	//this 指针 
	Complex m(this->real-n.real,this->image-n.image);
	return(m);//此时间点,系统自动调用复制构造函数 
}
int main(void)  
{
	 Complex a(1.8,-2.4),b(4.3,4.7);
	 Complex c=a.add(b);  //给对象赋初值的又一方式 
	 Complex d=a.sub(b);
	 c.print();
	 d.print();
	 //e=a+b
	 Complex e;
	 e=a+b; //加法运算符重载,编译器自动转化成
	 //e=a.operator+(b) 
	 //e.operator=(z的中间块)系统默认写 
	 cout<<"++++++加法 运算符重载结果"<<endl;
	 e.print(); 
	 cout<<"------------- 减法运算符重载函数"<<endl; 
	 Complex f;
	 f=a-b; 
	f.print();	

}

原创文章 7 获赞 10 访问量 272

猜你喜欢

转载自blog.csdn.net/lpblog/article/details/105736348