9.5 (C++)

Define the Complex class.

输入
5.8
6.2

输出
++ c1 = 6.8 + 6.2 i
c1 ++ = 6.8 + 6.2 i
real = 7.8

主程序 (不能修改)

#include <iostream>
using namespace std;

#include "source.cpp"

int main(){
    Complex c1;
    cin >> c1;
    cout << "++ c1 = " << ++ c1 << endl; // 实部 += 1
    cout << "c1 ++ = " << c1 ++ << endl; // 实部 += 1
    double real = c1; // 获取实部
    cout << "real = " << real << endl;
}

我的答案

class Complex
{
    double real,imag;
public:
    Complex(){
        real=0;
        imag=0;
    }
    
    Complex(double a,double b){
        this->real=a;
        this->imag=b;
    }
    
    friend ostream & operator<<( ostream & os,const Complex & c);
    friend istream & operator>>( istream & is,Complex & c);
    
    Complex operator ++ (){
        ++real;
        return *this;
    }
    
    Complex operator ++ (int a){
        Complex A(real,imag);
        ++real;
        return A;
    }
    operator double(){
        return this->real;
    }
};

ostream & operator<<( ostream & os,const Complex & c)
{
    os << c.real << " + " << c.imag << " i"; //输出复数
    return os;
}

istream & operator>>( istream & is,Complex & c)
{
    is>>c.real;
    is>>c.imag;
    return is;
}
上一篇: 9.2 (C++) 下一篇: 8.5 (C++)
支持 makedown语法