cpp 面向对象初步探索

需求

尝试定义一个complex(复数类)

简略实现

headers/complex.h

#ifndef __COMPLEX__
#define __COMPLEX__

class complex
{
public:
    complex(double re=0, double im=0):real(re), imag(im)
    { }

    complex& operator += (const complex &other) {
        this->real += other.real;
        this->imag += other.imag;
        return *this;
    }

    double get_real();
    double get_imag();

private:
    double real;
    double imag;
};

double complex::get_real() {
    return this->real;
}

double complex::get_imag() {
    return this->imag;
}
#endif // __COMPLEX__

main.cpp

#include <iostream>
#include "headers/complex.h"
using namespace std;

int main()
{
    complex c1(2, 3);
    complex c2(3, 4);
    c1 += c2;
    cout << c1.get_imag();
    cout << c1.get_real();
}
posted @ 2019-09-15 17:27 Draymonder 阅读(...) 评论(...) 编辑 收藏