小编son*_*s10的帖子

如何用类的参数重载运算符 +?

我正在学习 C++ 中的重载运算符,并且我已经完成了关于由实部和虚部形成的两个虚数之和的代码。

#include<iostream> 
using namespace std; 

class Complex { 
private: 
    int real, imag; 
public: 
    Complex(int r, int i) {
        real = r; 
        imag = i;
    } 


    Complex operator + (Complex const &num1, Complex const &num2) { 
        Complex res; 
        res.real = num1.real + num2.real; 
        res.imag = num1.imag + num2.imag; 
        return res; 
    } 

    void print() { 
        cout << real << " + i" << imag << endl; 
    } 
}; 

int main() 
{ 
    Complex c1(10, 5), c2(2, 4); 
    Complex c3 = c1 …
Run Code Online (Sandbox Code Playgroud)

c++ oop class operator-overloading object

0
推荐指数
1
解决办法
252
查看次数

标签 统计

c++ ×1

class ×1

object ×1

oop ×1

operator-overloading ×1