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

在C++中,运算符重载允许我们为自定义类型(如类)赋予标准运算符新的行为。通过重载,可以让对象像基本数据类型一样使用+、-、==等操作符,提升代码可读性和易用性。
什么是运算符重载
运算符重载是函数重载的一种形式,它使我们能重新定义已有运算符对类对象的操作方式。例如,两个复数对象可以通过+直接相加,而不是调用add()函数。
基本规则和限制
不是所有运算符都能被重载,比如 ::(作用域解析)、.(成员访问)、.*、?: 和 sizeof 不能重载。重载后的运算符不能改变优先级或结合性。
立即学习“C++免费学习笔记(深入)”;
可以作为类的成员函数或全局函数重载至少有一个操作数必须是用户自定义类型重载函数应保持自然语义,避免滥用
实例:复数类的加法与输出重载
下面是一个完整的例子,展示如何重载 + 和
#include using namespace std;class Complex {private:double real, imag;public:Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 成员函数重载加法(也可用友元或全局函数)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 <= 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
c2 = 1 - 2i
c1 + c2 = 4 + 2i
重载赋值运算符 =
当类涉及动态资源管理时,必须自定义赋值运算符以防止浅拷贝问题:
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] = ' '; } }// 赋值运算符重载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]; }// 重载[],支持读写int& operator[](int index) { if (index = size) { throw out_of_range("Index out of bounds"); } return arr[index];}~IntArray() { delete[] arr; }
};
使用示例:
IntArray a(5);
a[0] = 10;
cout
基本上就这些常见用法。掌握运算符重载能让自定义类型更直观、更接近内置类型的行为,但要合理使用,避免造成误解。
以上就是c++++ 运算符重载代码 c++ operator重载实例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1488130.html
微信扫一扫
支付宝扫一扫