【参考文章】
[1] C++运算符重载
[3] C++的new和delete详解
1、首先一个Demo
#include "iostream"
#include "string"
using namespace std;
class base {
public:
int a;
base(int m_a) :a(m_a) {
cout << "base()" << endl;
}
};
int main()
{
base a(10);
base b(10);
base c = a + b;
cout << c.a << endl;
}
报错指向非常清晰,对于base类不存在“+”的操作运算。
2、实现operator+,实现对象+操作
way1:友员实现,全局有效
way2:成员函数实现,只对类有效
// way:友员函数实现
#include "iostream"
#include "string"
using namespace std;
class base {
public:
int a;
base(int m_a) :a(m_a) {
cout << "base()" << endl;
}
friend base& operator+(base &a, base &b);
};
base& operator+(base &a, base &b)
{
a .a= a.a + b.a;
return a;
}
int main()
{
base a(10);
base b(10);
base c = a + b;
cout << c.a << endl;
}
way2:成员函数实现重载
运算符左边的是 this,右边的是 other,运算符加操作数的整个表达式的返回值就是返回值
#include "iostream"
#include "string"
using namespace std;
class base {
public:
int a;
base(int m_a) :a(m_a) {
cout << "base()" << endl;
}
base& operator+(base &b);
};
base& base::operator+(base &b)
{
b.a= this->a + b.a;
return b;
}
int main()
{
base a(10);
base b(10);
base c = a + b;
cout << c.a << endl;
}
3、可以进行重载的操作符
双目算术运算符 | + (加),-(减),*(乘),/(除),% (取模) |
关系运算符 | ==(等于),!= (不等于),< (小于),> (大于),<=(小于等于),>=(大于等于) |
逻辑运算符 | ||(逻辑或),&&(逻辑与),!(逻辑非) |
单目运算符 | + (正),-(负),*(指针),&(取地址) |
自增自减运算符 | ++(自增),--(自减) |
位运算符 | | (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移) |
赋值运算符 | =, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>= |
空间申请与释放 | new, delete, new[ ] , delete[] |
其他运算符 | ()(函数调用),->(成员访问),,(逗号),[](下标) |
不可以进行重载的运算符
- .:成员访问运算符
- .*, ->*:成员指针访问运算符
- :::域运算符
- sizeof:长度运算符
- ?::条件运算符
- #: 预处理符号
重载实现形式:
刚在上面说了,重载操作符函数实现有两种方式,一个是友员函数,另一个是类的成员函数,那么哪些操作符重载使用第一种,哪些使用第二种呢?
- 操作符[]、->、=、(),只能通过使用类的成员函数方式来实现操作符重载
- 操作符<<、>>,只能使用友员函数来实现
- 其余暂无约束,两种方式均可
4、new、delete重载
5、重载实现的原理
why:为何操作a+b能够自动识别使用我们所实现的operator+方法呢?
what:
how: