강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

호두님의 프로필 이미지
호두

작성한 질문수

홍정모의 따라하며 배우는 C++

9.8 형변환을 오버로딩 하기

[00:39] 형변환을 오버로딩할 때는 리턴타입은 지정을 안해주나요?

작성

·

191

2

안녕하세요.

operator int()

{

cout << "cast here" << endl;

return m_cents;

}

이렇게 해주려고 하니까

C++ return type may not be specified on a conversion function

int() 요게 컨버전 함수인가요?

감사합니다.

===자답====

답을 찾았습니다.

주소: https://www.learncpp.com/cpp-tutorial/910-overloading-typecasts/

There are two things to note:

  1. To overload the function that casts our class to an int, we write a new function in our class called operator int(). Note that there is a space between the word operator and the type we are casting to.
  2. User-defined conversions do not take parameters, as there is no way to pass arguments to them.
  3. User-defined conversions do not have a return type. C++ assumes you will be returning the correct type.

그리고 여기 있는 내용을 보다가 궁금한 게 생겼는데요.

User-defined conversions allow us to convert our class into another data type. Take a look at the following class:

This class is pretty simple: it holds some number of cents as an integer, and provides access functions to get and set the number of cents. It also provides a constructor for converting an int into a Cents.

If we can convert an int into a Cents, then doesn’t it also make sense for us to be able to convert a Cents back into an int? In some cases, this might not be true, but in this case, it does make sense.

int를 Cents로 변환하는 생성자를 제공한다.

이 개념은 또 처음이라서요 (제가 놓쳤을 수도 있습니다)

저는 그냥 생성자에서 클래스의 멤버 변수를 초기화만 해주고 있다고 생각했었어요.

이건 어떻게 봐야할까요?

감사합니다.

답변 2

2

홍정모님의 프로필 이미지
홍정모
지식공유자

Cents(int cents = 0)이 마치 생성자 두 가지를 구현한 것 처럼 작동한다는 표현입니다.

0

홍정모님의 프로필 이미지
홍정모
지식공유자

Cents(아무것도 없음), Cents(int cents)

호두님의 프로필 이미지
호두

작성한 질문수

질문하기