只能在引用基类时调用的方法? C++
假设我有一个抽象类
class NecessaryDanger
{
public:
virtual void doSomethingDangerous() =0;
}
和一个从该类派生的类:
class DoesOtherStuff : public NecessaryDanger
{
//stuff
void otherMethod();
void doSomethingDangerous();
}
有没有一种方法我只能允许访问 doSomethingDangerous() 就像
DoesOtherStuff d;
d = DoesOtherStuff();
d.otherMethod(); //OK
d.doSomethingDangerous(); //error
NecessaryDanger* n = &d;
n->doSomethingDangerous(); //OK
我不太擅长 C++ 一样,所以上面的代码可能不太正确,但是你也许明白了。我有一组类需要能够执行“危险的事情”(以它们自己的特殊方式),如果这些类的多个对象执行这种危险的操作,则可能会导致问题。我想要一个管理器类,它有一个仅指向一个对象的 NecessaryDanger 指针。如果 doSomethingDangerous 方法只能由 NecessaryDanger 对象调用,那么意外调用 doSomethingDangerous 的情况就更难发生,并导致我日后头疼。
预先感谢您的帮助。如果这是一个愚蠢的问题,请提前抱歉!
Say I have an abstract class
class NecessaryDanger
{
public:
virtual void doSomethingDangerous() =0;
}
and a class that is derived from this class:
class DoesOtherStuff : public NecessaryDanger
{
//stuff
void otherMethod();
void doSomethingDangerous();
}
is there a way I can only allow access of doSomethingDangerous() like
DoesOtherStuff d;
d = DoesOtherStuff();
d.otherMethod(); //OK
d.doSomethingDangerous(); //error
NecessaryDanger* n = &d;
n->doSomethingDangerous(); //OK
I am not very good at C++ yet, so the code above may not be quite right, but you maybe get the idea. I have a set of classes that need to have the ability to do "something dangerous" (in their own special way) that could cause problems if more than one object of these classes does this dangerous thing. I would like to have a manager class that has a NecessaryDanger pointer to only one object. If the method doSomethingDangerous could only be called by a NecessaryDanger object, then it would be more difficult for an accidental call to doSomethingDangerous to happen and cause me headaches down the road.
Thanks in advance for the help. Sorry in advance if this is a dumb question!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然。只需在派生类中将其设置为
private
,在基类中将其设置为public
即可。当然,如果
NecessaryDanger
是公共基地,那么任何人都可以施放和调用。您可能希望将其设为私人基地并使用friend
。Sure. Just make it
private
in the derived class andpublic
in the base.Of course, if
NecessaryDanger
is a public base, then anyone can cast and call. You might want to make it a private base and usefriend
.删除超类中的虚拟分类器,以便编译器根据变量类型进行编译时绑定,而不是根据对象类型进行运行时绑定。
Remove the
virtual
classifier in the superclass so that the compiler does compile-time binding based on the variable type instead of run-time binding based on the object type.以 Potatswatter 的回应为基础 :)
这里是 Herb 的建议:(尤其是 1 和 2)适用在此背景下。
Building on Potatswatter's response :)
Here is Herb's advice: (especially 1 and 2) applicable in this context.