개발 공부/알고리즘

HackerRank, C++, Overload Operators

그냥하는티스토리 2022. 11. 3. 20:55
728x90

operator 를 직접 짜본 것도 처음이다.

다만 이걸 실제로 쓸 때가 있으려나,

엄밀히 말하면, c++ 개발이 아니라 c개발자라서 안쓰는 걸수도 ,,

c++은 알면 알수록 복잡도가 어마 어마하다.

//Overload operators + and << for the class complex
//+ should add two complex numbers as (a+ib) + (c+id) = (a+c) + i(b+d)
//<< should print a complex number in the format "a+ib"
Complex operator+ ( Complex a , Complex b)
{
    int aRe = a.a + b.a;
    int bRe = a.b + b.b;
    string result = to_string(a.a+b.a) +"+i" + to_string(a.b + b.b);
    
    Complex *newObj = new Complex;
    newObj->input(result);
    return *newObj; 
}
ostream& operator<<(ostream& os, Complex x)
{
    os << x.a << "+i" << x.b;
    return os;
}
728x90