Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ 重载运算符

作者:吃斋的狼   发布日期:2025-03-21   浏览:66

// C++ 重载运算符示例

#include <iostream>
using namespace std;

class Complex {
private:
    double real;
    double 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);

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

// 实现 << 运算符的重载
ostream& operator<<(ostream& os, const Complex& c) {
    os << c.real << " + " << c.imag << "i";
    return os;
}

int main() {
    Complex c1(3.5, 4.2);
    Complex c2(2.1, 3.7);

    Complex c3 = c1 + c2;  // 使用重载的 + 运算符
    cout << "c1 + c2 = " << c3 << endl;

    if (c1 == c2) {  // 使用重载的 == 运算符
        cout << "c1 and c2 are equal" << endl;
    } else {
        cout << "c1 and c2 are not equal" << endl;
    }

    return 0;
}

解释说明:

  1. 构造函数Complex 类有一个构造函数,可以初始化复数的实部和虚部,默认值为 0。
  2. 重载 + 运算符:通过成员函数 operator+ 实现两个复数相加的功能,返回一个新的 Complex 对象。
  3. 重载 << 运算符:通过友元函数 operator<< 实现将 Complex 对象输出到流(如 cout)中。这里使用了 friend 关键字,因为我们需要访问私有成员 realimag
  4. 重载 == 运算符:通过成员函数 operator== 实现两个复数是否相等的判断。
  5. 主函数:在 main 函数中,我们创建了两个 Complex 对象,并演示了如何使用重载的运算符进行加法和相等性比较。

希望这个示例能帮助你理解 C++ 中的运算符重载!

上一篇:vc++runtime

下一篇:c++ 正则表达式

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站