당신은 Engine
개체가 Car
const
에 의해 p
을 지적 할 것이다 회원 Engine
const*
등을 수정할 수 있습니다
test_const.cpp:12:9: error: member function 'Power' not viable: 'this' argument
has type 'const Engine', but function is not marked const
p->Power();
^
test_const.cpp:3:10: note: 'Power' declared here
void Power(){
^
을하지만이 의미 :
class Engine{
public:
void Power(){
}
};
class Car{
public:
Car() : p(new Engine()){}
void Accelerator() const{
p->Power();
}
private:
Engine const* p;
};
이 더 이상 컴파일되지 않습니다 Car
의 구성원이 *p
을 수정할 수 없다는 것은 사용자가 의도하지 않은 것일 수 있습니다. 더 나은 답변을 원한다면 @ NathanOliver의 의견을 참조하십시오.
희망이 도움이됩니다.
당신의'Engine' 포인터가'const'하지가 가리키는하는 일이기 때문입니다. – AndyG
'Engine'대신 'Engine *'이 필요한 이유가 있습니까? – NathanOliver
실제 차량에는 엔진이 포함되어있을뿐 아니라 하나를 가리킬 수 있습니다. –