栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

2022.6.16 C++——运算符的重载(-/=等一些运算符)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2022.6.16 C++——运算符的重载(-/=等一些运算符)

1. 运算符-重载

还是用Complex例子
示例:

class Complex
{
private:
	int Real;
	int Image;
public:
	Complex() :Real{ 0 }, Image{ 0 }
	{
		cout << "Create Complex" << this << endl;
	}
	Complex(int r, int i) :Real{ r }, Image{ i }
	{
		cout << "Create Complex(int int)" << this << endl;
	}
	Complex(const Complex& com) :Real(com.Real), Image(com.Image)
	{
		cout << "Copy Create Complex(const Complex&)" << this << endl;
	}
	~Complex()
	{
		cout << "Destroy Complex" << this << endl;
	}
	void Print() const
	{
		cout << "Real= " << Real << " Image= " << Image << endl;
	}
	Complex operator-(const Complex& com) const
	{
		int r = this->Real - com.Real;
		int i = this->Image - com.Image;
		return Complex(r, i);
	}
};

运行结果:

结果分析:
在程序运行中,执行cc = ca.operator-(cb);时,其实编译器底层执行的是cc=ca-cb;//cc=ca.operator-(cb);//cc=operator(&ca,cb);,这就可以很清楚的知道减法运算法在编译器底层的运行情况,也更容易理解程序。
注意:在调用类中operator-(形参)函数时,我们要求调用其实现两个类对象进行相加,不需要改变这两个类对象的值,只需要将相加后的值给另外一个对象就行,因此,在写类函数——减法运算符函数时,给形参前边加上const,在对象前面加上引用符,即:形参是一个常引用,这个函数执行程序中加上const,如:

2. 运算符+=重载

只需要将上述代码中的减法运算符操作函数变为+=运算符操作函数,+=函数如:

Complex &operator+=(const Complex& com)
	{
		this->Real += com.Real;
		this->Image += com.Image;//+=要改变ca的值
		return *this;
	}

其与+函数不同的是,在程序执行中,不需要加const,例如执行this->Real += com.Real;时,是将 this->Real + com.Real;值不停的赋值给this->Real,如果在程序执行中加入const,说明最后的值不能变化,那么+=这个函数就有问题了。
注意:在c++中,operator+=是一个合法的函数名。在这个函数中,返回值是*this而不是com,如果返回值是com的话,那么相当于执行代码this->Real += com.Real时,执行完后返回的是com.Real,这是错误的。
运行结果:

int main中,执行cc = ca += cb;时,编译器底层其实执行的顺序为://ca+=cb;//ca.operator+=(cb);//operator+=(&ca,cb);//cc=operator+=(&ca,cb);

3. 运算符-=重载

-=运算符和+=运算符是一样的,只不过在程序中的工作不一样,-=运算符在工作中,是将两个成员进行减法运算。
代码如下:

Complex& operator-=(const Complex& com)
	{
		this->Real -= com.Real;
		this->Image -= com.Image;//+=要改变ca的值
		return *this;
	}

运行结果:

执行cc = ca -= cb;时,编译器底层执行的是://ca-=cb;//ca.operator-=(cb);//operator-=(&ca,cb);//cc=operator-=(&ca,cb);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/976817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号