강의

멘토링

커뮤니티

Inflearn Community Q&A

it09kim's profile image
it09kim

asked

Following and Learning C++ with Hong Jeong-mo

13.1 Function Templates

const 질문입니다

Resolved

Written on

·

207

0

안녕하세요

#include "Cents.h"

using namespace std;

template<typename T>
T getMax(T x, T y)
{
	return (x > y) ? x : y;
}



int main()
{
	cout << getMax(1, 2) << endl;
	cout << getMax(3.14, 1.592) << endl;
	cout << getMax(1.0f, 3.4f) << endl;
	cout << getMax('a','c') << endl;

	std::cout << getMax(Cents(5), Cents(9)) << std::endl;
	return 0;
}

#pragma once

#include <iostream>	

class Cents
{
private:
	int m_cents;

public:
	Cents(int cents)
		:m_cents(cents)
	{}

	friend bool operator > (const Cents &c1, const Cents &c2)
	{
		return (c1.m_cents > c2.m_cents);
	}

	friend std::ostream &operator << (std::ostream &out,  const Cents &cents)
	{
		out << cents.m_cents << " cents";
		return out;
	}

};

전체 코드입니다.

Cents 클래스 내에서 operator > 와 operator <<  함수에서

operator > 함수 파라미터에선 const 없이

friend bool operator > (Cents &c1, Cents &c2)

{

return ( c1.m_cents > c2.m_cents);

}

가 가능 한데

operator << 함수 파라미터에서 const 없이

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

{

out << cents.m_cents << " cents";

return out;

}

이렇게 할 경우 에러가 나는데 

const 붙여서 수정 못하게 할 때 붙이는줄 알았는데

어떤 차이 인가요..?

계속 질문드려서 죄송합니다 ㅜ 

C++

Answer 1

4

질문자님께서 최근에 올리신 https://www.inflearn.com/questions/227874  질문글에서 제가 답변으로 const 참조는 R-value 또한 참조가 가능하다고 말씀드렸습니다. 또한 일반 참조는 R-value 를 참조할 수 없다는 것도 앞에서 배우셨을 겁니다.

함수는 언제나 R-value 로 리턴을 합니다.(리턴 타입이 Cent& 와 같은 참조가 아니라면 언제나 R-value 입니다.)

매개변수를 const 없애고 그냥 일반 참조인  Cents& cents 로 한다면 << 연산자의 파라미터로는 L-value 인 Cents 객체만 올 수 있다는 얘기에요. 근데 getMax(Cents(5), Cents(9)) 이 함수가 리턴하는건 R-value 인 Cents 객체이죠? 그러니 일반 참조 타입인 Cents& cents 매개변수로 함수 리턴값 (R-value) 를 받을 수가 없는겁니다. 그래서 R-value인 Cents 파라미터를 받을 수 있는 << 연산자 오버로딩은 없으니 오류가 뜨는거에요. R-value 객체도 파라미터로 받을 것이라면 const 참조는 R-value 를 참조할 수 있기 때문에 const 붙여주는게 좋겠습니다. 

이 질문 또한 이전에 답변드린 내용으로 설명이 되는 내용이니 다시 참고해보셨으면 합니다

+ const 참조가 왜 R-value 를 참조할 수 있는지에 대해서 다른 질문글에 자세하게 답변 작성한적이 있습니다. 링크도 한번 참고해주세요 https://www.inflearn.com/questions/144487

it09kim님의 프로필 이미지
it09kim
Questioner

감사합니다!

operator << 에선 왜 안되는지 확실히 알았습니다

그럼 operator > 에서는

template<typename T>
T getMax(T x, T y)
{
	return (x > y) ? x : y;
}

여기서 익명 객체를 받아서 x ,y 라는 메모리를 복사해서 넘겨주기때문에 L-value로

받아져서 const 없이 가능한건가요?

네 맞습니다

it09kim's profile image
it09kim

asked

Ask a question