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

operator在c++中怎么用

作者:屰兲洏垳&   发布日期:2026-02-17   浏览:14

#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);
    }

    // 重载减法操作符 (-)
    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 << "i";
        return os;
    }
};

int main() {
    Complex c1(3.0, 4.0);
    Complex c2(1.0, 2.0);

    Complex sum = c1 + c2;  // 使用重载的加法操作符
    Complex diff = c1 - c2; // 使用重载的减法操作符

    cout << "c1: " << c1 << endl;
    cout << "c2: " << c2 << endl;
    cout << "c1 + c2: " << sum << endl;
    cout << "c1 - c2: " << diff << endl;

    return 0;
}

解释说明:

  1. 类定义Complex 类用于表示复数,包含两个私有成员变量 realimag 分别表示复数的实部和虚部。
  2. 构造函数Complex(double r = 0, double i = 0) 提供了默认值为 0 的构造函数。
  3. 操作符重载
    • operator+:重载了加法操作符,使得两个 Complex 对象可以直接相加。
    • operator-:重载了减法操作符,使得两个 Complex 对象可以直接相减。
    • operator<<:重载了输出流操作符,使得可以使用 cout 输出 Complex 对象。
  4. 主函数:在 main 函数中,创建了两个 Complex 对象 c1c2,并演示了如何使用重载的操作符进行加法和减法运算,最后输出结果。

上一篇:c++ map初始化

下一篇:c++ 函数

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++框架代码

c++格式化字符串

c++ orm框架

c++ find_if

c++ random函数用法

队列c++

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

Laravel 中文站