-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
해결됨
안녕하세요 질문입니다
21.06.08 17:51 작성 조회수 117
1
#pragma once
#include <string>
#include "Position2D.h"
class Monster
{
private:
std::string m_name; // char * data, unsigned length;
Position2D m_location;
//int m_x; // location
//int m_y;
public:
Monster(const std::string name_in, const Position2D & pos_in)
:m_name(name_in), m_location(pos_in)
{
}
//void moveTo(const int &x_target, const int &y_target)
//{
// m_x = x_target;
// m_y = y_target;
//}
void moveTo(const Position2D &pos_target)
{
//m_x = x_target;
//m_y = y_target;
m_location.set(pos_target);
}
friend std::ostream &operator << (std::ostream &out, Monster &monster)
{
out << monster.m_name << " " << monster.m_location << std::endl;
return out;
}
};
값 변경이 안되게 하는거 같은데 상수화하는것 같은데
moveTo 함수 내에서 파라미터로 const를 빼면 왜 안되는것인지 궁금합니다
operator << 함수에선 const 를 안붙여도 되는건가요?
그리고
#pragma once
#include <iostream>
class Position2D
{
private:
int m_x;
int m_y;
public:
Position2D(const int& x_in, const int & y_in)
:m_x(x_in), m_y(y_in)
{}
// TODO: overload operator =
void set(const Position2D & pos_target) // 파라미터 왜 const
{
set(pos_target.m_x, pos_target.m_y);
// m_x = pos_target.m_x;
// m_y = pos_target.m_y;
}
void set(const int &x_target, const int &y_target)
{
m_x = x_target;
m_y = y_target;
}
friend std::ostream &operator << (std::ostream &out, Position2D &Position2D)
{
out << Position2D.m_x << " " << Position2D.m_y << std::endl;
return out;
}
};
마찬가지로 여기선 operator << 함수에 파라미터중 Position2D에 const를 안붙여도되나요?
너무 헷갈리는데 어디부분을 복습해야할까요..
답변을 작성해보세요.
3
안소
2021.06.10
"moveTo 함수 내에서 파라미터로 const를 빼면 왜 안되는것인지 궁금합니다
operator << 함수에선 const 를 안붙여도 되는건가요?"
👉 6단원 에서 배우셨을 "const 참조"는 R-value, L-value 모두 참조할 수 있습니다. const 떼고 그냥 참조로 하면 L-value 파라미터만 받을 수 있구요, const 붙이면 R-value 파라미터"도" 받을 수 있습니다. 그리고 수정이 불가능해지구요! 이런 차이를 고려해서 const 붙일지 안붙일지 결정하면 됩니다. 익명 객체같은건 R-value 이니 moveTo 는 파라미터로 익명 객체를 받을 수 있겠네요!
👉 출력 스트림에 출력할 내용을 집어넣으면서 출력 스트림 객체에 어떤 "변화"가 생기기 때문에 ostream 타입인 out 매개변수는 const 붙으면 안되구요(수정을 못하게되니까요), Position2D& Position2D 에는 객체 내용 수정 안할거라면 const 붙이든 안붙이든 상관없습니다. 위에서 설명드린대로 R-value 객체도 파라미터로 받게 할거라면 const 반드시 붙여야겠지만요!
"마찬가지로 여기선 operator << 함수에 파라미터중 Position2D에 const를 안붙여도되나요?"
👉 위에서 설명이 될 것 같네요.
답변 1