C++ 重载

22 阅读1分钟

一、定义

  • 在同一作用域内,允许存在多个同名标识符(函数、运算符等),但要求它们的 “特征信息” 不同,编译器会根据调用场景自动匹配对应的实现

二、条件

  • 参数个数不同;
  • 参数类型不同;
  • 参数顺序不同(仅当类型不同时有效,纯参数名顺序不同无效)。

三、案例

  1. 运算符重载
#include <iostream> 
using namespace std; 
class Point { 
public: 
int x, y; 
Point(int x = 0, int y = 0) : x(x), y(y) {} 
// 成员函数重载 + 运算符(this 指向左操作数 p1) 
Point operator+(const Point& p) const { //若const存在,不允许该当前对象

return Point(this->x + p.x, this->y + p.y); // 返回新对象 
} 
}; 
int main() { 
Point p1(1, 2), p2(3, 4); 
Point p3 = p1 + p2; // 等价于 p1.operator+(p2) 
cout << "p3: (" << p3.x << ", " << p3.y << ")" << endl; // 输出 (4, 6) 
return 0;
}