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++中为用户定义的类型重载关系运算符和算术运算符,使这些类型的对象能够像内置类型一样使用这些运算符。

相关推荐
tjl521314_216 小时前
04C++ 名称空间(Namespace)
开发语言·c++
ximu_polaris6 小时前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式
tankeven11 小时前
C++ 智能指针
c++
handler0113 小时前
【算法模板】最小生成树:稠密图选 Prim,稀疏图选 Kruskal
c语言·数据结构·c++·算法
许长安13 小时前
RPC 异步调用基本使用方法:基于官方helloworld-async 示例
c++·经验分享·笔记·rpc
sparEE14 小时前
c++面向对象:对象的赋值
开发语言·c++
此生决int14 小时前
快速复习之数据结构篇——栈和队列
数据结构·c++
H_BB14 小时前
第17届蓝桥杯备战历程
c++·算法·职场和发展·蓝桥杯
daad77714 小时前
记录一次上下文切换次数的统计
服务器·c++·算法
tankeven15 小时前
C++ Lambda 表达式
c++