Getter를 사용하여 공개 VAR에 액세스 할 수없는 이유는 무엇입니까?

StackOverflow https://stackoverflow.com/questions/2055486

  •  20-09-2019
  •  | 
  •  

문제

이 진술을 포함하는 파일이있는 :

public:
boost::shared_ptr<TBFControl::TbfCmdHandler> _tbfCmdHandlerPtr;
// will be private later...

boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler()
{ return _tbfCmdHandlerPtr; }

이런 식으로 사용할 수 있습니다.

boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandlerPtr(
    this->getTBFInstallation()-> _tbfCmdHandlerPtr );

그러나 내가 원하는 것처럼 이런 식으로 :

boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandlerPtr(
    this->getTBFInstallation()->getTBFCmdHandler() );

Getter 기능을 사용하면 다음 오류가 발생합니다.

'하우스 키핑 :: tbfinstallation :: gettbfcmdhandler': 'const housekeeping :: tbfinstallation'에서 '이'포인터를 '하우스 키핑 :: tbfinstallation &'로 변환 할 수 없습니다.

여기서 무엇이 잘못되고 있습니까?

도움이 되었습니까?

해결책

확실히, this->getTBFInstallation() Const 포인터를 반환합니다. 기능을 만들어야합니다 getTBFCmdHandler Const.

boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler() const
{
    return _tbfCmdHandlerPtr;
}

참고 const 첫 번째 줄의 끝에 키워드.

편집하다: 추가하여 const, 당신은 사실상 유형을 바꾸고 있습니다 this ~에서 TBFInstallation * 에게 TBFInstallation const *. 기본적으로, const, 당신은 함수가 호출되는 객체가 const 일 때에도 함수를 호출 할 수 있다고 말합니다.

다른 팁

getTBFInstallation() (명백히) Const 포인터를 반환하고 있습니다. 하지만, getTBFCmdHandler() 비 정통 회원 기능이므로 Const 포인터에서 호출 할 수 없습니다. 해결책 : make getTBFCmdHandler() const 멤버 함수

코드를 보지 않고 나는 그것을 추측 할 것이다 getTBFInstallation() 반환 a const TBFInstallation 비 Const 기능을 호출하려고합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top