【发布时间】:2011-02-16 07:05:26
【问题描述】:
所以也许这是一个愚蠢的问题,我想多了,但我有以下情况。我正在制作一个“class Shell”,它可以运行抽象的“class Action”对象。它是唯一应该创建或使用这些对象的类。 Action 对象需要访问 Shell 才能对其执行特定操作,但我试图避免为此添加公共接口(不应允许其他人这样做)。
我原本有一个简单的(不那么优雅)
class Shell
{
public:
bool checkThing();
// etc...
private:
bool _thing;
};
class Action
{
public:
virtual void execute( Shell &s )=0;
};
class ChangeAction : public Action
{
public:
void execute( Shell &s )
{
// requires friendship or public mutator!
s._thing = true;
}
};
所以我考虑了一个嵌套类 Action,但我想将其设为私有(为什么要让除了 Shell 之外的任何其他人做出具体的 Action,对吧?)
class Shell
{
public:
bool checkThing();
// etc...
private:
bool _thing;
class Action;
};
class Shell::Action
{
public:
virtual void execute( Shell &s )=0;
};
class ChangeAction : public Shell::Action
{
public:
void execute( Shell &s )
{
// ok now!
s._thing = true;
}
};
但我当然不能再从 Action 继承(这是有道理的,它是私有的)。所以这行不通。
所以我的问题是,我应该使用第一种方法和友谊还是公共界面?我可以使用类似于第二种方法的方法来保持与 Actions 和 Shell 的关系吗? 你有更好的主意吗?
【问题讨论】:
标签: c++ inheritance friend nested-class