Lab 1: Class Helloworld

顯示 Complex Class 的數字

  • 輸入:無
  • 輸出:顯示 Complex Class 的數字
  • 檔名:lab1_<學號>.cpp (e.g. lab1_106062802.cpp)

程式僅需輸出兩 complex 數字 a 及 b 以及 c = a + b 的結果。

Format

(a) = a1 + a2 i
(b) = b1 + b2 i
(c) = a + b = c1 + c2 i

Example

$ ./a.out
(a) = 1 + 2 i
(b) = 3 + -4 i
(c) = (a) + (b) = 4 + -2 i

Pseudo Code

#include <iostream>

using namespace std;

class Complex
{
public:
    int real;
    int imag;
    friend ostream &operator<<(ostream &os, const Complex &c)
    {
        os << c.real << " + " << c.imag << " i";
        return os;
    }
    void print() const
    {
        // TODO: implement this function
        // Hint: use cout to print the complex number.
        // use 'real' and 'imag' as the real and imaginary part
        // of the complex number.
    }
    Complex &operator+(const Complex &c)
    {
        real += c.real;
        imag += c.imag;
        return *this;
    }
};

int main()
{
    Complex a, b, c;

    a.real = 1;
    a.imag = 2;
    cout << "(a) = " << a << endl;

    b.real = 3;
    b.imag = -4;
    cout << "(b) = ";
    b.print();
    cout << endl;

    c = a + b;
    cout << "(c) = (a) + (b) = " << c << endl;

    return 0;
}