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

转载于:https://www.cnblogs.com/Draymonder/p/11523520.html

你可能感兴趣的:(cpp 面向对象初步探索)