关键字 operator
定义: 对已有的运算符进行重定义,赋予另一种功能
分为: 成员函数重载 和 全局函数重载
1.加法运算符重载
class person {
friend void run();//设置友元
private:
int num;;
public:
person(int num) {
this->num = num;
}
person& operator+(person per) {
//加法运算符重载
this->num += per.num;
return *this;
}
};
void run() {
person p1(10);
person p2(10);
person p3=p1 + p2;
cout << p3.num;//20
}
int main() {
run();
}
递增运算符重载
class Person {
friend ostream& operator<<(ostream& cout, Person p);//设置友元
private:
int num;
public:
Person() {
num = 0;
}
//前置递增运算符
Person& operator++() {
this->num++;
return *this;
};
//后置递增运算符
//Person operator++(int) int代表占位参数,可用与前值和后置递增
//次处返回值不要用引用,因为temp位局部变量,会在函数执行完后释放,而且后置递增运算符本身也不可连用
Person operator++(int) {
Person temp = *this;//记录本身的值
this->num++;
return temp;
}
};
ostream& operator<<(ostream& cout, Person p) {//重载左移运算符
cout << p.num ;
return cout ;
}
void run() {
Person p;
cout << p<< endl;//0
cout << p++ << endl;//0
cout << p << endl;//1
cout << ++p << endl;//2
}
int main() {
run();
}
赋值运算符重载
主要解决问题,和之前的构造拷贝函数一致,问了解决堆内存重复释放问题
class Person {
friend void run();
private :
int* p;
public :
Person(int age) {
p = new int(age);
}
~Person() {
if (p != NULL) {
delete p;
p = NULL;
}
}
//编译器本身提供浅拷贝
Person& operator=(Person &f) {//赋值运算符重载
//先判断堆区中是否存留属性,有的话,先释放在深拷贝
if (this->p != NULL) {
delete this->p;
}
this->p = new int(*f.p);
return *this;
}
};
void run() {
Person f(9);
Person p(10);
Person z(11);
cout << *f.p << endl;//9
cout << *p.p << endl;//10
f = p;
cout << *f.p << endl;//10
f = p = z;
cout << *f.p << endl;//11
}
int main() {
run();
}
函数调用运算符重载(仿函数)
class Myadd {
public:
int operator()(int a, int b) {
return a + b;
}
};
int add(int a, int b) {
return a + b;
}
int main() {
int sum1=add(8, 2);//函数
cout << sum1 << endl;//10
Myadd myadd;
int sum2 = myadd(1, 2);// 因为与函数相像所以称之为仿函数(使用()重载)
cout << sum2 << endl;//10
//顺便提及一下 匿名函数对象
int sun 3 = Myadd()(10,10);//10
}
来源:CSDN
作者:秃头侠客
链接:https://blog.csdn.net/qq_44620773/article/details/104739302