inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Học C++ cùng Hong Jeong-mo

9.3 Quá tải các toán tử một ngôi

초급한 질문이라 죄송합니다.

359

작성자 없음

0 câu hỏi đã được viết

0

우선 강의 중 몇분 몇초 부분이라 정하기 어려운 질문입니다 ㅠ

고민을 아무리 해봐도 답을 찾이 못해서 남깁니다.

입출력연산자 오버로딩에서 아래와 같이 const 를 빼고 Cents &cents 로 받으면

std::ostream &operator << (std::ostream &out, Cents &cents)

단항 연산자가 붙지 않으면 cout << cents1 << endl; 는 출력이 되고

cout << -cents1 << endl; 는 왜 출력이 안될까요?ㅠ

const 쪽 강의를 다시 들어도,, 디버거로 찍어보며 천천히 따라가도 이유를 모르겠어서 질문 남깁니다 .

감사합니다.

C++

Câu trả lời 5

3

skf346

윗 분 말씀처럼 rvalue와 관련이 있습니다.

-cents는 Cents(-m_cents)를 return하는데 이건 익명 객체이죠. 익명 객체(Cents(10) 등)는 rvalue로 여겨지는데 함수로 pass rvalue를 하려면 parameter는 const reference만 가능합니다.

rvalue를 왜 const reference로만 받아야 하는가에 대해서는 아래 링크에 설명되어있습니다.

https://stackoverflow.com/questions/36102728/why-is-it-allowed-to-pass-r-values-by-const-reference-but-not-by-normal-referenc?newreg=af09de2f1d8d479ca830d2af2a5cb732

한 가지 예시가 나오는데

void display(int& a) { a = 10 };

display(1);

가 있다면 말 그대로 a = 10은 rvalue에 rvalue를 넣으라는 말입니다. 말이 안되죠.

따라서 질문자님이 말씀하신 reference만 사용할 수 없습니다

그럼 왜 const가 이 역할을 하는가는 c++의 feature로 인한것 같습니다.

Q1: Is the following code legal C++?

// Example 1

string f() { return "abc"; }

void g() {
const string& s = f();
  cout << s << endl;    // can we still use the "temporary" object?
}

A1: Yes.

This is a C++ feature… the code is valid and does exactly what it appears to do.

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by f() lives until the closing curly brace. (Note this only applies to stack-based references. It doesn’t work for references that are members of objects.)

Does this work in practice? Yes, it works on all compilers I tried (except Digital Mars 8.50, so I sent a bug report to Walter to rattle his cage :-) and he quickly fixed it for the Digital Mars 8.51.0 beta).

Q2: What if we take out the const… is Example 2 still legal C++?

// Example 2

string f() { return "abc"; }

void g() {
string& s = f();       // still legal?
  cout << s << endl;
}

A2: No.

The "const" is important. The first line is an error and the code won’t compile portably with this reference to non-const, because f() returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.

요약하자면 const reference는 temporary object(rvalue)의 수명을 연장시켜 준다고 합니다. reference로만 받았을 때는 그 수명이 해당 expression에만 머물러 문제가 발생합니다.

덕분에 저도 찾아보면서 많은 공부가 되었습니다!

혹시 잘못된 내용있으면 답변으로 수정 부탁드립니다.

2

gptapikorea

컴파일 단계부터 오류가 생기더라구요 ㅠ 오류가 생기는 이유를 모르겠습니다.ㅠㅠ - 가 연산자 인것과 const를 붙이는 것과의 연관성을 모르겠습니다. const는 그 영역 안에서 변수가 바뀔 일이 없을때 붙여주는것으로 알고있는데 붙이지 않아도 컴파일 단계오류는 생기면 안되지 않나요?ㅠ

1

thd2tn

6.15 강의를 보시면 더 자세하게 알 수 있으실 거 같은데 Cents& cents는 literal로는 초기화가 안되지만 const Cents& cents는 literal로 초기화가 될 수 있어서 발생하는 문제인 거 같습니다.

0

hodu

김준성님 이 문제 혹시 해결하셨나요? 

0

honglab

-cents1할 때 -도 연산자라서 오퍼레이터 오버로딩을 해줘야할텐데, 컴파일할때 오류가 안생겼었나요?

변수가 메모리에 저장되는 것을 알려주는 강의가 어떤강의였죠

1

466

1

메모리 주소 10진수로 출력

1

653

1

클래스 템플릿 특수화에서 boolalpha로 표현된 리턴값에 대해 질문이 있습니다.

1

499

1

여러가지 리턴 타입에 관한 강의가 어떤 걸까요?

1

534

1

메모리 주소에 관한 질분

0

679

1

인터페이스 클래스에서 reportError의 매개변수에 대해 궁금한 것이 있습니다.

0

549

1

형변환 오버로딩에서 const 관련 질문이 있습니다.

0

443

1

Digit 뒤에 reference를 사용하는 이유

0

510

1

4.2 전역 변수, 정적 변수, 내부 연결, 외부 연결

0

323

1

dat파일이...

0

539

1

TODO:대입 연산자 오버로딩에 대한 소스코드입니다.

0

644

1

복사 생성자 관련 질문이 있습니다.

0

454

1

수업 중 궁금한점이 있습니다.

1

390

1

라이브러리자체가 이해가 되지 않습니다.

0

561

1

마지막 예제 질문

0

302

1

증감연산자 위치에 따른 수행 순서 질문입니다.

0

375

1

단항 연산자 오버로딩에서 return 부분에 질문이 있습니다.

1

411

1

friend함수 관련 질문이 있습니다.

0

312

1

operator+ 정의부분에서 궁금한 것이 있습니다.

0

447

1

3분 17초 질문

0

350

1

함수에 값을 대입한다는 개념이 이해가 되지 않습니다.

0

448

1

int getvalue() const에서 const는 왜 뒤에 붙는건가요?

0

445

2

const Something &st에서 const를 빼면 안되나요?

0

300

1

friend함수는 다른 클래스의 멤버함수로 쓸 수 없나요??

1

493

1