在C++中,运算符重载是一种允许开发者重新定义已有运算符的行为的特性,通过运算符重载可以为自定义的类类型或者枚举类型定义运算符的操作。
加减乘除
这里以加法为例子,其他类似
#include <iostream>
class MyNumber {
private:
int value;
public:
MyNumber(int val) : value(val) {}
MyNumber operator+(const MyNumber& other) {
return MyNumber(value + other.value);
} //成员函数版本重载运算符+
int getValue() const {
return value;
}
};
MyNumber operator+(const MyNumber& num1,const MyNumber& num2) {
return MyNumber(num1.val + num2.val);
}//全局函数版本重载运算符+
int main() {
MyNumber num1(5);
MyNumber num2(10);
MyNumber result = num1 + num2; // 调用重载的加法运算符
std::cout << "Result: " << result.getValue() << std::endl;
return 0;
}
左移运算符重载
需要注意的是,左移运算符重载需要返回的的仍旧是ostream类型因为要实现链式调用
#include<iostream>
using namespace std;
class MyClass;
class MyClass {
// friend ostream& operator<<(ostream& os,const MyClass& obj);
private:
int a;
public:
MyClass(int a) : a(a) {}
friend ostream& operator<<(ostream& os,const MyClass& obj){ //第一个参数就是cout,第二个参数就是obj 对应为cout << obj 并且返回还是cout,所以可以链式调用
//要用友元函数,因为cout是全局的,而a是私有的,所以不能直接访问,故要用友元函数
os << "Data" << obj.a;
return os;
}
};
//利用全局函数重载左移运算符,不过因为是私有,故也要加一个友元
// ostream& operator<<(ostream& os,const MyClass& obj){
// os << "Data" << obj.a;
// return os;
// }
int main(){
MyClass obj(10);
cout << obj << "hello" << endl;
return 0;
}
递增递减重载
这两者是一样的,故只展示一下递增重载的写法
#include<iostream>
using namespace std;
class MyClass {
private:
int a;
public:
MyClass(int a) : a(a) {}
MyClass& operator++(){ //前置返回的是该对象,不是值不会发生拷贝创建新对象
this->a ++;
return *this;
}
MyClass operator++(int){ //后置++,参数int为占位符,不过此时返回的还是原来的数字
MyClass temp = *this;
this->a++;
return temp;
}
friend ostream& operator<<(ostream& os, const MyClass& obj){
os << obj.a;
return os;
}
int getA(){
return this -> a;
}
};
int main(){
MyClass obj(10);
++obj;
cout << obj++ << endl; //11
cout << obj.getA() << endl;//12
return 0;
}
赋值运算符重载
这里进行深拷贝的重载,防止因为浅拷贝而导致的内存重复释放
#include<iostream>
using namespace std;
class A{
public:
int* a;
A(){
a = new int(10);
}
~A(){
if(a!=NULL){
delete a;
a = NULL;
}
}
void operator=(const A& p){
//先判断是否有属性在堆区,如果有先释放干净,再进行深拷贝,否则之前的空间没进行回收,造成内存泄漏
if(a!=NULL){
delete a;
a = NULL;
}
this->a = new int(*p.a);
// 不过也可以直接拿之前的内存空间
// *(this->a) = *(p.a);
}
};
int main(){
A b;
A c;
c.a = new int(20);
b = c;
cout << *(b.a) << endl;
cout << *(c.a) << endl;
}
函数调用重载 () ----也称为仿函数
使用起来非常像一个函数调用,故称为仿函数,下面举一个例子
#include <iostream>
using namespace std;
class Adder {
public:
int operator()(int a, int b) {
return a + b;
}
};
int main() {
Adder add;
int sum = add(5, 3); // 调用重载的函数调用运算符
cout << "Sum: " << sum << endl;
return 0;
}