为什么我不能使用getter访问public var?

Chr*_*erw 0 c++ boost shared-ptr

有一个包含这些语句的文件:

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

boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler()
{ return _tbfCmdHandlerPtr; }
Run Code Online (Sandbox Code Playgroud)

我可以这样使用它:

boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandlerPtr(
    this->getTBFInstallation()-> _tbfCmdHandlerPtr );
Run Code Online (Sandbox Code Playgroud)

但不是,就像我想要的那样:

boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandlerPtr(
    this->getTBFInstallation()->getTBFCmdHandler() );
Run Code Online (Sandbox Code Playgroud)

使用getter函数,会发生以下错误:

'Housekeeping :: TBFInstallation :: getTBFCmdHandler':无法将'this Housekeeping :: TBFInstallation'中的'this'指针转换为'Housekeeping :: TBFInstallation'

这里出了什么问题?

ava*_*kar 7

显然,this->getTBFInstallation()返回一个const指针.你还需要使用getTBFCmdHandlerconst函数.

boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler() const
{
    return _tbfCmdHandlerPtr;
}
Run Code Online (Sandbox Code Playgroud)

请注意const第一行末尾的关键字.

编辑:通过添加const,你实际上改变的类型this,从TBFInstallation *TBFInstallation const *.基本上,通过添加const,你可以说即使调用函数的对象是const,也可以调用该函数.