C++重载机制深度解析:函数重载与运算符重载全攻略
C++允许同一作用域内对函数名或运算符给出多个定义,分别称为函数重载与运算符重载。重载声明:同名、同作用域、参数列表不同(类型/个数/顺序),返回类型不同不构成重载。调用时编译器通过重载决议匹配最佳版本。
函数重载
同名函数,参数列表不同。示例:print()处理int/double/char*:
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) { cout << "Printing int: " << i << endl; }
void print(double f) { cout << "Printing float: " << f << endl; }
void print(char* c) { cout << "Printing character: " << c << endl; }
};
int main() {
printData pd;
pd.print(5); // 调用int版
pd.print(500.263); // 调用double版
pd.print("Hello C++"); // 调用char*版
return 0;
}
输出:Printing int: 5、Printing float: 500.263、Printing character: Hello C++
运算符重载
重新定义内置运算符行为,使其支持用户自定义类型。重载运算符本质是特殊命名的函数:operator + 运算符符号。如:
Box operator+(const Box&); // 成员函数形式,隐含this指针
// 或非成员函数形式
Box operator+(const Box&, const Box&);
成员函数重载+实现Box相加示例:
#include <iostream>
using namespace std;
class Box {
public:
double getVolume() { return length * breadth * height; }
void setLength(double len) { length = len; }
void setBreadth(double bre) { breadth = bre; }
void setHeight(double hei) { height = hei; }
// 重载+:this为左操作数,b为右操作数
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length, breadth, height;
};
int main() {
Box Box1, Box2, Box3;
Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0);
Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0);
cout << "Volume of Box1 : " << Box1.getVolume() << endl; // 210
cout << "Volume of Box2 : " << Box2.getVolume() << endl; // 1560
Box3 = Box1 + Box2; // 调用operator+
cout << "Volume of Box3 : " << Box3.getVolume() << endl; // 5400
return 0;
}
可重载/不可重载运算符
可重载(共计约40个):
| + | - | * | / | % | ^ |
| & | | | ~ | ! | , | = |
| < | > | <= | >= | ++ | -- |
| << | >> | == | != | && | || |
| += | -= | /= | %= | ^= | &= |
| |= | *= | <<= | >>= | [] | () |
| -> | ->* | new | new[] | delete | delete[] |
不可重载(4个):
| :: | .* | . | ?: |
运算符重载分类示例索引
| 序号 | 重载类型 |
|---|---|
| 1 | 一元运算符重载 |
| 2 | 二元运算符重载 |
| 3 | 关系运算符重载 |
| 4 | 输入/输出运算符重载 |
| 5 | ++/--运算符重载 |
| 6 | 赋值运算符重载 |
| 7 | 函数调用()运算符重载 |
| 8 | 下标[]运算符重载 |
| 9 | 类成员访问->运算符重载 |
各类详细实现见后续专题章节。
C语言