运算符重载是C++中通过函数重载为类定义操作符行为的机制,使对象能像基本类型一样使用+、-等操作。它本质是函数重载,不改变优先级、结合性或操作数个数。可通过成员函数实现左操作数为类对象的运算(如a + b),或通过友元函数支持对称操作和非类对象左操作数(如5.0 + c)。常见示例包括重载赋值=避免浅拷贝、下标[]提供元素访问、前置与后置++区分用int占位符。不可重载的运算符有.、.*、::、?:和sizeof。应保持原有语义,合理使用以提升代码可读性与类的自然性。

在C++中,运算符重载是一种允许我们为自定义类型(如类或结构体)重新定义已有运算符行为的机制。通过运算符重载,我们可以让对象像基本数据类型一样使用+、-、==等操作符,使代码更直观、易读。
运算符重载的本质是函数重载。它允许我们为特定的类定义某个运算符的具体实现方式。比如,可以让两个Complex(复数)对象直接用+相加。
需要注意的是,运算符重载不能改变运算符的优先级、结合性或操作数个数,也不能创建新的运算符。
运算符重载可以通过成员函数或非成员函数(通常为友元函数)来实现,具体选择取决于运算符的类型和需求。
立即学习“C++免费学习笔记(深入)”;
1. 成员函数形式
适用于左操作数是当前类对象的情况,常用于=、[]、()、->以及一元运算符(如++、--)等必须作为成员函数的运算符。
例如,重载+运算符:
class Complex {
public:
double real, imag;
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 成员函数重载 +
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}};
使用方式:
Complex a(3, 4), b(1, 2); Complex c = a + b; // 调用 a.operator+(b)
2. 友元函数形式
当需要对称性操作(如a + b 和 b + a都合法),或者左操作数不是类对象时(如int + Complex),推荐使用友元函数。
例如,支持double + Complex:
class Complex {
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 声明友元运算符函数
friend Complex operator+(double d, const Complex& c);};
// 定义友元函数 Complex operator+(double d, const Complex& c) { return Complex(d + c.real, c.imag); }
这样就可以写:Complex result = 5.0 + c;
1. 赋值运算符 =
如果类管理资源(如指针),需要显式定义赋值运算符以避免浅拷贝问题。
class MyString {
char* data;
public:
MyString& operator=(const MyString& other) {
if (this == &other) return *this; // 自赋值检查
delete[] data;
data = new char[strlen(other.data) + 1];
strcpy(data, other.data);
return *this;
}
};2. 下标运算符 []
常用于容器类,返回指定位置元素的引用。
class MyArray {
int arr[10];
public:
int& operator[](int index) {
return arr[index]; // 可读可写
}
const int& operator[](int index) const {
return arr[index]; // 只读版本
}
};3. 前置与后置 ++
区分前置和后置的关键在于参数:后置版本多一个int占位符。
class Counter {
int count;
public:
// 前置++
Counter& operator++() {
++count;
return *this;
}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 后置++
Counter operator++(int) {
Counter old = *this;
++count;
return old;
}};
.、.*、::、?:、sizeof等<<和>>只能用友元函数实现基本上就这些。掌握运算符重载能显著提升类的可用性和自然性,但要合理使用,确保逻辑清晰、行为一致。
以上就是c++++怎么重载运算符_c++运算符重载实现方法详解的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号