运算符重载允许为类或结构体重新定义+、-、==等运算符行为,使对象能像基本类型一样进行操作。

在C++中,运算符重载是一种允许我们为自定义类型(如类或结构体)重新定义已有运算符行为的机制。通过运算符重载,我们可以让对象像基本数据类型一样使用+、-、==、
运算符重载本质上是函数重载的一种形式,使用关键字 operator 后跟要重载的符号来定义函数。
基本语法如下:
返回类型 operator符号(参数列表) {
// 实现逻辑
}
例如,重载加法运算符:
立即学习“C++免费学习笔记(深入)”;
class Complex {
public:
double real, imag;
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
<pre class='brush:php;toolbar:false;'>// 成员函数方式重载 +
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}};
运算符可以作为成员函数或友元函数重载,选择取决于具体场景。
成员函数重载:
友元函数重载:
示例:用友元函数重载 }; std::ostream& operator<<(std::ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
class Complex {
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
<pre class='brush:php;toolbar:false;'>friend std::ostream& operator<<(std::ostream& out, const Complex& c);
以下是一些常用运算符的重载方式:
赋值运算符 =
需要手动实现深拷贝,防止资源重复释放。
Complex& operator=(const Complex& other) {
if (this != &other) {
real = other.real;
imag = other.imag;
}
return *this;
}
比较运算符 ==
bool operator==(const Complex& other) const {
return real == other.real && imag == other.imag;
}
下标运算符 []
必须作为成员函数,常用于数组类封装。
int& operator[](int index) {
return data[index]; // 假设 data 是内部数组
}
基本上就这些。掌握运算符重载能显著提升类的可用性和自然性,但应合理使用,避免过度“炫技”影响可维护性。
以上就是c++++中如何重载运算符_c++运算符重载方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号