小甲鱼-C++快速入门笔记 25 运算符重载1

写在前面:作为一只小白,感谢小甲鱼老师提供这么好的入门课程。因此在这里做个笔记,如有侵权请联系删除

www.fishc.com

https://blog.csdn.net/qq_30708445/article/details/88596720

 

所谓重载,就是重新赋予新的含义。函数重载就是对一个已有的函数赋予新的含义,使之实现新的功能。

而运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,以实现相应的运算。运算符重载时通过定义函数实现的,运算符重载实质上是函数的重载。

重载运算符的函数一般格式如下:

例如我们重载运算符+,如下:

int operator+(int a,int b)
{
    return (a-b);
}

举个例子:实现复数加法

(3,4i)+(5,-10i)=(8,-6i)

不用重载:

#include <iostream>
 
using namespace std;
 
class Complex
{
public:
	Complex();
	Complex(double r, double i);  //带参数的构造函数
	Complex complex_add(Complex &d);
	void print();
 
private:
	double real;
	double imag;
};
 
Complex::Complex()
{
	real = 0;
	imag = 0;
}
 
Complex::Complex(double r, double i)
{
	real = r;
	imag = i;
}
 
Complex Complex::complex_add(Complex &d)
{
	Complex c;
 
	c.real = real + d.real;
	c.imag = imag + d.imag;
 
	return c;
}
 
void Complex::print()
{
	cout << "(" << real << "," << imag << "i)\n";
}
 
int main()
{
	Complex c1(3, 4), c2(5, -10), c3;
	
	c3 = c1.complex_add(c2);
 
	cout << "c1 = ";
	c1.print();
	cout << "c2 = ";
	c2.print();
	cout << "c1 + c2 = ";
	c3.print();
 
	return 0;
}

使用运算符重载:

#include <iostream>
 
using namespace std;
 
 
// 演示对运算符"+"进行重载达到目的!
 
class Complex
{
public:
	Complex();
	Complex(double r, double i);  //带参数的构造函数
	Complex operator+(Complex &d);  //运算符重载
	void print();
 
private:
	double real;
	double imag;
};
 
Complex::Complex()
{
	real = 0;
	imag = 0;
}
 
Complex::Complex(double r, double i)
{
	real = r;
	imag = i;
}
 
Complex Complex::operator+(Complex &d)
{
	Complex c;
 
	c.real = real + d.real;
	c.imag = imag + d.imag;
 
	return c;
}
 
void Complex::print()
{
	cout << "(" << real << "," << imag << "i)\n";
}
 
int main()
{
	Complex c1(3, 4), c2(5, -10), c3;
	
	c3 = c1 + c2;
 
	cout << "c1 = ";
	c1.print();
	cout << "c2 = ";
	c2.print();
	cout << "c1 + c2 = ";
	c3.print();
 
	return 0;
}

我们在声明Complex类的时候对运算符进行了重载,使得这个类在用户编程的时候可以完全不考虑函数是如何实现的,直接用+,-,*,/ 进行复数的运算即可。

其实还可以:

Complex Complex::operator+(Complex &2)
{
    return Complex(real + c2.real, imag + c2.imag);
}

一些规则:

(1)C++不允许用户自己定义新的运算符,只能对已有的C++运算符进行重载

(2)除了对以下运算符不允许重载外,其他运算符允许重载:

--- .(成员访问运算符)

--- .*(成员指针访问运算符)

--- ::(域运算符)

--- sizeof (尺寸运算符)

--- ?:(条件运算符)

(3) 重载不能改变运算符运算对象(操作数)个数

(4) 重载不能改变运算符的优先级别

(5) 重载不能改变运算符的结合性

(6) 重载运算符的函数不能有默认参数

(7) 重载运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应该有一个是类对象或类对象的引用。(也就是说,参数不能全部都是C++的标准类型,这样约定是为了防止用户修改用于标准类型结构的运算符性质)。

课后作业:

重载运算符"+","-","*","/"实现有理数的加减乘除运算。

有理数:任何可以用分数来表示的就是有理数

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值