본문 바로가기

프로그래밍 언어/C, C++

[Hackerrank] 40. Overload Operators

40. Overload Operators

[ 난이도: Easy | 분야: Other Concepts ]

1. 과제

과제 설명

Complex라는 클래스가 다음과 같이 주어져 있다:

class Complex
{
	public:
    	int a,b;
};

연산자들은 특별한 이름의 정규 함수인 operator function으로 오버로드 되어 있다. 이 함수의 이름은 오버로드된 연산자 기호 뒤에 파라미터를 붙이는 것으로 정의된다.

구문은 다음과 같다:

type operator sign (parameters) { /* ... body ... */ }

Complex 클래스에서는 + 연산자와 << 연산자를 오버로드 해야 한다.

연산자 +는 다음의 복소수 합 규칙에 따라 결과를 반환한다:

(a+ib) + (c+id) = (a+c) + i(b+d)

stream insertion 연산자를 오버로드하여 a+ib를 출력한다.

cout << c << endl;

위 구문은 새로운 줄에 a+ib를 출력해야 한다.

여기서 a = c.a 이고 b = c.b이다.

 

입력 형식

오버로드 연산자 +는 두 개의 복소수를 파라미터로 받는다. ( a+ib 그리고 c+id)

이 함수는 반드시 단일의 복소수를 반환한다.

오버로드 연산자 <<는 a+ib를 stream으로 출력한다. 여기서 a는 복소수의 실수부, b는 복소수의 허수부다.

 

출력 형식

각 문제마다, a = c.a, b = c.b로 새로운 줄에 출력해라.

 

입력 예시

3+i4
5+i6

 

출력 예시

8+i10

 

설명

연산자 +를 오버로딩한 결과가 8+i10이다.

 

문제

//Operator Overloading

#include<iostream>

using namespace std;

class Complex
{
public:
    int a,b;
    void input(string s)
    {
        int v1=0;
        int i=0;
        while(s[i]!='+')
        {
            v1=v1*10+s[i]-'0';
            i++;
        }
        while(s[i]==' ' || s[i]=='+'||s[i]=='i')
        {
            i++;
        }
        int v2=0;
        while(i<s.length())
        {
            v2=v2*10+s[i]-'0';
            i++;
        }
        a=v1;
        b=v2;
    }
};

//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"

int main()
{
    Complex x,y;
    string s1,s2;
    cin>>s1;
    cin>>s2;
    x.input(s1);
    y.input(s2);
    Complex z=x+y;
    cout<<z<<endl;
}
더보기

정답

//Operator Overloading

#include<iostream>

using namespace std;

class Complex
{
public:
    int a,b;
    void input(string s)
    {
        int v1=0;
        int i=0;
        while(s[i]!='+')
        {
            v1=v1*10+s[i]-'0';
            i++;
        }
        while(s[i]==' ' || s[i]=='+'||s[i]=='i')
        {
            i++;
        }
        int v2=0;
        while(i<s.length())
        {
            v2=v2*10+s[i]-'0';
            i++;
        }
        a=v1;
        b=v2;
    }
};

//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 &x, Complex &y) {
    int my_real_x = x.a;
    int my_real_y = y.a;
    int my_imagine_x = x.b;
    int my_imagine_y = y.b;
    Complex z;
    z.a = my_real_x + my_real_y;
    z.b = my_imagine_x + my_imagine_y;
    return z;
}

ostream& operator<<(ostream& out, Complex &z){
    out << z.a << "+i" << z.b;
    return out;
};

int main()
{
    Complex x,y;
    string s1,s2;
    cin>>s1;
    cin>>s2;
    x.input(s1);
    y.input(s2);
    Complex z=x+y;
    cout<<z<<endl;
}

 

 

 

 

 

©️Hackerrank. All Rights Reserved.