gpt4 book ai didi

c++如何为同一成员创建公共(public)和 protected 访问器

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:22 25 4
gpt4 key购买 nike

如果我有两种方法 - 一种是公共(public)的,一种是 protected 返回对同一成员的引用,我会得到以下编译错误:

'Server::getManager': cannot access protected member declared in class 'Server'

当我注释掉 protected 函数时,代码可以正常工作。你能告诉我为什么会这样吗?为什么编译器找不到相同成员的公共(public)函数?

class Manager
{
};

class Server
{
public:
const Manager & getManager() const { return m_man; }
protected:
Manager & getManager() { return m_man; } // <-- after removing this method I get no compilation error

private:

Manager m_man;
};

int main()
{

Server s;
const Manager& m = s.getManager();
return 0;
}

最佳答案

Why the compiler cannot find the public function to same member?

这不是问题。编译器找到两个 函数并执行重载决策以确定哪个是最佳可行候选者。两位候选人是:

Manager&       getManager()        // protected
Manager const& getManager() const // public

对于成员函数,有一个隐含的第一个对象参数,它是类本身的实例。在这种情况下,这两个函数变为:

getManager(Server& )         // protected
getManager(Server const& ) // public

我们在一个不是 const 的对象 (s) 上调用它。两个候选者都是可行的,但是 public 候选者比 protected 引用了一个更多 cv 限定的对象candidate - 所以它不太受欢迎。标准语在 [over.ics.rank] 中:

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if
— S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

因此,protected 候选者是首选 - 所以它就是被调用的那个。

不幸的是,它是 protected,所以调用它是错误的。重载决议后检查访问控制。所以你必须以某种方式重组你的程序。您可以简单地将 s 转换为 const:

const Manager& m = const_cast<Server const&>(s).getManager();

这将使 protected 候选者不可行。

关于c++如何为同一成员创建公共(public)和 protected 访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37103718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com