강의

멘토링

커뮤니티

Inflearn Community Q&A

jiwon33461212's profile image
jiwon33461212

asked

Following and Learning C++ with Hong Jeong-mo

9.5 Overloading Increment and Decrement Operators

후위 연산자에서 this가 아닌 다른 인스턴스에 왜 주소가 아닌 값을 넘겨주면 안되나요?

Written on

·

224

0

    Digit operator ++ (int

    {

        Digit temp(m_digit);

        ++(*this);

        return temp;

    }

 

이렇게 주소를 넘겨주는 건 되는데 왜

  Digit& operator ++ (int

    {

        Digit temp(m_digit);

        ++(*this);

        return *temp;

    }

저렇게 값을 넘겨주면

Indirection requires pointer operand

와 같은 에러가 발생되는 건지 모르겠어요.

C++

Answer 2

0

Digit& operator ++ (int

    {

        Digit temp(m_digit);

        ++(*this);

        return *temp;

    }

함수 안에서 정의된 temp라는 instance의 scope는 함수 내부가 됩니다. 함수를 벗어나게 되면 소멸하게 되는 거죠.

reference로 반환을 하려면 원본이 존재해야하는데 함수 밖을 나가면 사라지는 temp를 return by reference하면 reference는 원본을 찾을 수 없습니다.

0

honglab님의 프로필 이미지
honglab
Instructor

    Digit operator ++ (int

    {

        Digit temp(m_digit);

        ++(*this);

        return temp;

    }

이렇게 주소를 넘겨주는 건 <-- temp는 instance입니다. 이 아래 부분은 글만 봐서는 어떤 부분에서 막히신 것인지를 이해하기가 어렵네요.

jiwon33461212's profile image
jiwon33461212

asked

Ask a question