C++ 关系运算符重载和算术运算符重载的例子,运算符重载必须以operator开头

在C++中,运算符重载允许为用户定义的类型(类或结构体)赋予某些内置运算符的功能。下面是一个关于关系运算符重载(==)和算术运算符重载(+)的简单例子。

示例:复数类的运算符重载

将创建一个表示复数的类,并为其重载==和+运算符。

【cpp】

#include

using namespace std;

class Complex {

private:

double real;

double imag;

public:

// 构造函数

Complex(double r = 0.0, double i = 0.0) : real®, imag(i) {}

复制代码
// 重载关系运算符 ==
bool operator==(const Complex& other) const {
    return (real == other.real && imag == other.imag);
}

// 重载算术运算符 +
Complex operator+(const Complex& other) const {
    return Complex(real + other.real, imag + other.imag);
}

// 用于打印复数
void print() const {
    if (imag < 0)
        cout << real << " - " << -imag << "i" << endl;
    else
        cout << real << " + " << imag << "i" << endl;
}

};

int main() {

Complex c1(3.0, 4.0);

Complex c2(3.0, 4.0);

Complex c3(1.0, 2.0);

复制代码
// 使用重载的 == 运算符
if (c1 == c2) {
    cout << "c1 is equal to c2" << endl;
} else {
    cout << "c1 is not equal to c2" << endl;
}

// 使用重载的 + 运算符
Complex c4 = c1 + c3;
cout << "c1 + c3 = ";
c4.print();

return 0;

}

解释

  1. 复数类定义:

    • Complex类有两个私有成员变量:real和imag,分别表示复数的实部和虚部。

    • 构造函数允许使用给定的实部和虚部初始化复数对象。

  2. 关系运算符重载:

【cpp】

bool operator==(const Complex& other) const {

return (real == other.real && imag == other.imag);

}

• 这个重载的==运算符比较两个复数对象的实部和虚部是否相等。

• const关键字表示该函数不会修改调用它的对象。

  1. 算术运算符重载:

【cpp】

Complex operator+(const Complex& other) const {

return Complex(real + other.real, imag + other.imag);

}

• 这个重载的+运算符返回一个新的Complex对象,其实部和虚部分别是两个操作数对应部分的和。

• 同样,const关键字表示该函数不会修改调用它的对象。

  1. 打印函数:

    • print方法用于格式化输出复数,根据虚部的正负决定输出形式。

  2. main函数:

    • 创建了几个Complex对象,并使用重载的==和+运算符进行比较和加法运算。

    • 结果通过cout输出。

这个例子展示了如何在C++中为用户定义的类型重载关系运算符和算术运算符,使这些类型的对象能够像内置类型一样使用这些运算符。

相关推荐
澈2075 小时前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
A.A呐5 小时前
【C++第二十九章】IO流
开发语言·c++
ambition202425 小时前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
kebeiovo5 小时前
atomic原子操作实现无锁队列
服务器·c++
Yungoal5 小时前
常见 时间复杂度计算
c++·算法
6Hzlia6 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
Ricky_Theseus6 小时前
C++右值引用
java·开发语言·c++
吴梓穆7 小时前
UE5 c++ 常用方法
java·c++·ue5
云栖梦泽7 小时前
Linux内核与驱动:9.Linux 驱动 API 封装
linux·c++
Morwit7 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展