文章目录
前言
C++运算符重载是面向对象三大特性之一多态的体现
本文章为初学者为巩固知识所创作,知识有限,大佬轻喷
一、什么是运算符重载
在C++中函数可以发生重载,让同一个函数名的函数通过传入不同参数从而实现不同的效果
运算符重载就是让不同类型的变量(对象)通过C++中运算符操作的时候产生不同的效果
举个栗子:
int类型的变量可以进行+ - * / (加减乘除) 等操作
比如:
int a = 0;
int b = a + 1;
a = a + b;
可是我们自己定义的数据类型能这么操作吗?
试试就逝世:
class Myclass
{
protected:
int i;
float f;
string str;
public:
Myclass(){
}
Myclass(int i, float f, string str)
{
this->i = i;
this->f = f;
this->str = str;
}
Myclass& output()
{
cout << "i=" << i << " f=" << f << " str=" << str << endl;
return *this;
}
};
void test()
{
Myclass object1(1,