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

c++重载运算符

作者:断晴星魂   发布日期:2025-04-02   浏览:42

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

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

    // 重载输出运算符
    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;
    Complex prod = c1 * c2;

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

    return 0;
}

解释说明

  1. 类定义:

    • Complex 类用于表示复数,包含两个私有成员变量 realimag 分别表示实部和虚部。
  2. 构造函数:

    • 构造函数 Complex(double r = 0, double i = 0) 允许创建复数对象,并可以初始化实部和虚部,默认值为 0。
  3. 重载加法运算符 (operator+):

    • operator+ 函数用于实现两个复数的相加操作。返回一个新的 Complex 对象,其实部为两个复数实部之和,虚部为两个复数虚部之和。
  4. 重载减法运算符 (operator-):

    • operator- 函数用于实现两个复数的相减操作。返回一个新的 Complex 对象,其实部为两个复数实部之差,虚部为两个复数虚部之差。
  5. *重载乘法运算符 (`operator`)**:

    • operator* 函数用于实现两个复数的相乘操作。根据复数乘法规则计算新的实部和虚部。
  6. 重载输出运算符 (operator<<):

    • operator<< 函数用于将 Complex 对象以指定格式输出到 ostream 对象(如 cout)。使用 friend 关键字使其成为友元函数,可以直接访问类的私有成员。
  7. 主函数 (main):

    • 创建两个 Complex 对象 c1c2,并演示了加法、减法和乘法运算的结果,最后通过重载的输出运算符将结果打印出来。

上一篇:c++ std::move

下一篇:c++常用函数

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ vector 清空

c++ tcp

c++ gcd函数

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

Laravel 中文站