运算符重载允许为类类型定义运算符行为,如复数类中重载+和

在C++中,运算符重载允许我们为自定义类型(如类)赋予标准运算符新的行为。通过重载,可以让对象像基本数据类型一样使用+、-、==等操作符,提升代码可读性和易用性。
运算符重载是函数重载的一种形式,它使我们能重新定义已有运算符对类对象的操作方式。例如,两个复数对象可以通过+直接相加,而不是调用add()函数。
不是所有运算符都能被重载,比如 ::(作用域解析)、.(成员访问)、.*、?: 和 sizeof 不能重载。重载后的运算符不能改变优先级或结合性。
立即学习“C++免费学习笔记(深入)”;
下面是一个完整的例子,展示如何重载 + 和
#include <iostream>
using namespace std;
<p>class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}</p><pre class='brush:php;toolbar:false;'>// 成员函数重载加法(也可用友元或全局函数)
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 友元函数重载输出流,访问私有成员
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << (c.imag >= 0 ? " + " : " - ") << abs(c.imag) << "i";
return os;
}};
int main() { Complex c1(3, 4); Complex c2(1, -2); Complex c3 = c1 + c2;
cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; cout << "c1 + c2 = " << c3 << endl; return 0;
}
输出结果:
c1 = 3 + 4i当类涉及动态资源管理时,必须自定义赋值运算符以防止浅拷贝问题:
class String {
private:
char* data;
public:
String(const char* str = nullptr) {
if (str) {
data = new char[strlen(str)+1];
strcpy(data, str);
} else {
data = new char[1];
data[0] = '\0';
}
}
<pre class='brush:php;toolbar:false;'>// 赋值运算符重载
String& operator=(const String& other) {
if (this == &other) return *this; // 自赋值检查
delete[] data; // 释放原内存
data = new char[strlen(other.data)+1];
strcpy(data, other.data);
return *this; // 支持链式赋值 a = b = c
}
~String() {
delete[] data;
}
friend ostream& operator<<(ostream& os, const String& s) {
os << s.data;
return os;
}};
常用于实现安全的数组类访问:
class IntArray {
private:
int* arr;
int size;
public:
IntArray(int s) : size(s) {
arr = new int[size];
}
<pre class='brush:php;toolbar:false;'>// 重载[],支持读写
int& operator[](int index) {
if (index < 0 || index >= size) {
throw out_of_range("Index out of bounds");
}
return arr[index];
}
~IntArray() { delete[] arr; }};
使用示例:
IntArray a(5);基本上就这些常见用法。掌握运算符重载能让自定义类型更直观、更接近内置类型的行为,但要合理使用,避免造成误解。
以上就是c++++ 运算符重载代码 c++ operator重载实例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号