• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

10:59 멤버 함수로서 연산자 오버로딩

23.07.26 11:43 작성 조회수 183

1

멤버함수로서 연산자 오버로딩을 할 때는 무조건 parameter가 하나이어야 하는거죠? (이게 그냥 rule인걸까요? 이해가 아니라 외워야 하는...)

standalone 함수일 때는 연산자 오버로딩할 때 parameter 갯수 상관없는 것 같은데 맞나요?

답변 2

·

답변을 작성해보세요.

2

Soobak님의 프로필

Soobak

2023.07.26

안녕하세요, 답변 도우미 Soobak 입니다.

네, 그렇습니다.
다만, 이러한 규칙을 단순히 암기하는 것 보다는, 설계의 원리 혹은 동작 방식, 클래스와 인스턴스 간의 상호작용 등을 통해 이해하는 것이 더 중요하다고 생각합니다.

  • 멤버 함수로서의 연산자 오버로딩

    : 이 경우, 해당 연산자 오버로딩 함수는 이미 그 객체가 속한 환경 및 범위 내에서 작동합니다.
    따라서, 이항 연산자인 operator + 을 멤버 함수로 오버로딩의 경우, 함수는 하나의 매개변수에 대한 정보만 알아도 괜찮습니다.
    this 인스턴스가 첫 번째 피연산자(좌항)가 되고, 매개변수는 연산의 두 번째 피연산자(우항)가 됩니다.

  • 비멤버함수 또는 friend 함수로서의 연산자 오버로딩

    : 이 경우, 연산자 함수는 객체의 환경 및 범위 밖에서 작동하므로, 모든 피연산자를 매개변수로 받아야 합니다.


다양한 방식으로 연산자 오버로딩을 실험해보시며 학습하시는 것도 재미있을 것 같습니다. 👍👍

yahoo님의 프로필

yahoo

질문자

2023.07.27

답변 감사합니다😀

0

dee_to님의 프로필

dee_to

2023.12.06

이럴 때는 비정형적인 예시를 하나 생각해보세요!

 

물론 논리적인 비약이 많이 섞여있지만, 그래도 저한테는 이해하는데 도움이 조금 되어서 같은 의문을 가지는 다른 분들께도 아주 조금이나마 도움이 되고자 글 남깁니당

 

 

오늘 저녁은 밥과 돼지고기를 먹고싶어요. 근데 저는(함수는) 지금 밖에(클래스 밖에) 있어서 밥도 못하고, 돼지고기도 따로 사야해요.

#include <iostream>
using namespace std;

class Outside
{
public:
    enum Cooking
    {
        RICE = 1,
        PORK,
    };

private:
    Cooking ingredient;

public:
    Outside(const Cooking ingredient)
        : ingredient{ingredient} {}
    
    Outside(const int ingredient)
        : ingredient{Cooking(ingredient)} {}

    Cooking get_ingredient() const {return ingredient;}
};

Outside operator + (Outside& o1, Outside& o2)
{
    return Outside(o1.get_ingredient() + o2.get_ingredient());
}


int main()
{
    Outside rice(Outside::RICE);
    Outside pork(Outside::PORK);

    if(Outside(pork + rice).get_ingredient() == 3)
        cout << "Complete!" << endl;
}

클래스 밖에 있는 함수는 돼지고기도 따로 구하고, 밥도 따로 구해서 식단을 마련해야 해요.

 

 

저는(함수는) 집 안에(클래스 안에) 있어요! 그래서 밥은 그냥 여기서 지으면 되고, 돼지고기만 구입하면 돼요!

#include <iostream>
using namespace std;

class Home
{
public:
    enum Cooking
    {
        RICE = 1,
        PORK,
    };

private:
    Cooking ingredient;

public:
    Home(const Cooking ingredient)
        : ingredient{ingredient} {}
    
    Home(const int ingredient)
        : ingredient{Cooking(ingredient)} {}

    Cooking get_ingredient() const {return ingredient;}

    Home operator + (Home& o1)
    {
        return Home(this->get_ingredient() + o1.get_ingredient());
    }
};


int main()
{
    Home rice(Home::RICE);
    Home pork(Home::PORK);

    if(Home(pork + rice).get_ingredient() == 3)
        cout << "Complete!" << endl;
}

함수가 클래스 안에 있으면, 밥은 그냥 집 안에 있는걸로 만들고(this), 돼지고기만 따로 구해서 식단으로 만들면 돼요!

 

 

지금 집 안에 있는 애는 제 친구에요. 물론 친하긴 하지만.. 집에 있는 쌀을 함부로 뒤적거리는건 예의가 아니겠죠? 친구가 둘 다 사온대요!

 

#include <iostream>
using namespace std;

class Outside
{
public:
    enum Cooking
    {
        RICE = 1,
        PORK,
    };

private:
    Cooking ingredient;

public:
    Outside(const Cooking ingredient)
        : ingredient{ingredient} {}
    
    Outside(const int ingredient)
        : ingredient{Cooking(ingredient)} {}

    Cooking get_ingredient() const {return ingredient;}

    friend Outside operator + (Outside& o1, Outside& o2)
    {
        return Outside(o1.get_ingredient() + o2.get_ingredient());
    }
};

int main()
{
    Outside rice(Outside::RICE);
    Outside pork(Outside::PORK);

    if(Outside(pork + rice).get_ingredient() == 3)
        cout << "Complete!" << endl;
}

비록 집 안에 있지만, 친구이기 때문에 집 안의 재료를 직접 참고할 순 없고, 쌀과 돼지고기를 직접 구해와야 해요.