gpt4 book ai didi

c++ - 变量 : Private vs Protected 的访问修饰符

转载 作者:行者123 更新时间:2023-11-28 01:09:22 25 4
gpt4 key购买 nike

我有一个案例,我找不到合适的解决方案。我需要有模板基类和一个对该基类做一些工作的管理器类。这是代码

class Base;

class Manager
{
public:
void DoSomethingTo(Base * bclass)
{
if(bclass->PrivateVar == 0)
// Some code
}
}

class Base
{
protected:
int PrivateVar;
friend class Manager;
};

template<class T>
class TempBase : public Base
{
private:
Manager * man;
public:
void DoWork()
{
PrivateVar = 0;
man->DoSomethingTo(this);
}
}

我的问题是 PrivateVar 变量实际上必须是 TempBase 私有(private)的,并且不能从派生自 TempBase 的类访问,但是因为我不能将它的指针传递给 Manager::DoSomethingTo(),所以我必须从基类派生它,基类必须拥有 PrivateVar。由于我在 TempBase 中使用 PrivateVar,它不能对 Base 私有(private),这使得它可以从 TempBase 的子类访问。

我如何编写 TempBase 类,使 PrivateVar 成为私有(private)成员,而它可以从 Manager::DoSomethingTo() 访问?

谢谢

最佳答案

首先,让我们开始火焰大战:

There is never a reason for an attribute of a class to be protected. It shall either be private (in most cases) or perhaps in some corner cases public. Note that because every derived classes would see a protected attribute, protected only brings a false sense of security: one cannot control any invariant on a protected attribute, so it's essentially a public one, with a comment Don't Touch on top of it.

既然已经说完了,我建议简单地将其更改为:

class Base {};
template <typename T> class TBase;

class DoKey { template <typename T> friend class TBase; DoKey(); };

class Manager
{
public:
void DoSomethingTo(Base& base, DoKey const& key);
};

template <typename T>
class TBase: public Base
{
public:
void Do()
{
Manager manager;
if (PrivateVar == 0) { manager.DoSomething(*this, DoKey()); }
}

private:
int PrivateVar;
};

通过将测试的责任委托(delegate)给变量的所有者,我们轻轻地绕开了所有的担忧。当然,如果我们需要多个类以类似的方式运行,那么我们可以在 Base 中引入一个纯虚拟的 void ShouldIDoSomething() const 并在 中检查它经理的方法。

关于c++ - 变量 : Private vs Protected 的访问修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4256024/

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