C++/C++ 예제

복소수 클래스 정의 – 캡슐화 실습 [C++]

언제나휴일 2020. 7. 14. 16:47
반응형

 

복소수 클래스 다이어그램

#include <string>
#include <iostream>
using namespace std;

class Complex
{
    double image;
    double real;
public:
    Complex(double real = 0, double image = 0)
    {
        SetReal(real);
        SetImage(image);
    }
    void SetReal(double value)
    {
        real = value;
    }
    void SetImage(double value)
    {
        image = value;
    }
    double GetReal()const
    {
        return real;
    }
    double GetImage()const
    {
        return image;
    }
    string ToString()const
    {
        char buf[256] = "";
        if ((real != 0) && (image != 0))
        {
            if (image > 0)
            {
                sprintf_s(buf, sizeof(buf), "%g+%gi", real, image);
            }
            else
            {
                sprintf_s(buf, sizeof(buf), "%g%gi", real, image);
            }
            return buf;
        }
        if (real != 0)
        {
            sprintf_s(buf, sizeof(buf), "%g", real);
            return buf;
        }
        if (image != 0)
        {
            sprintf_s(buf, sizeof(buf), "%gi", image);
            return buf;
        }
        return "0";
    }
};

int main(void)
{
    Complex c1;
    Complex c2(2.1);
    Complex c3(2.1,3.3);
    Complex c4(0, 3.3);
    Complex c5(2.1, 0);
    Complex c6(2.1, -3.3);

    cout << "c1:" << c1.ToString() <<endl;
    cout << "c2:" << c2.ToString() << endl;
    cout << "c3:" << c3.ToString() << endl;
    cout << "c4:" << c4.ToString() << endl;
    cout << "c5:" << c5.ToString() << endl;
    cout << "c6:" << c6.ToString() << endl;
    return 0;
}

실행 결과

c1:0
c2:2.1
c3:2.1+3.3i
c4:3.3i
c5:2.1
c6:2.1-3.3i
반응형