更改方法的保护级别是否被视为良好实践?
换句话说,如果我有一堂课
class A
{
public:
A() { .. }
virtual void somemethod() { .. }
};
可以写吗
class B : public A
{
public:
B() { .. }
protected:
virtual void somemethod() { .. }
};
?或者这种方法有一些缺点吗?
In other words if I have a class
class A
{
public:
A() { .. }
virtual void somemethod() { .. }
};
is it ok to write
class B : public A
{
public:
B() { .. }
protected:
virtual void somemethod() { .. }
};
or are there some drawbacks with this approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这种方法的主要缺点是,人们总是可以获取 A 的指针/引用并调用公共的
somemethod
。你为什么要做这样的事?如果B
是A
,并且A
有一个 publicsomemethod
那么做B
。The main drawback with that approach is that one can always take a pointer/reference to
A
and invokesomemethod
where is public. Why would you want to do such thing? IfB
is anA
, andA
s have a publicsomemethod
then so doB
s.我想说这违背了多态性的目的,因为当你编写一个接受多态类型的函数时,派生类型应该与它同样工作:
恕我直言,这取决于你试图解决的具体问题,因为我不知道相信“永远”成功的“最佳实践”。
I would say this defeats the purpose of polymorphism, because when you write a function that accepts a polymorphic type, the derived type should work equally well with it:
IMHO, it depends on the specific problem you are trying to solve because I don't believe in "always" successful "best practice".
这种方法没有缺点。唯一的限制是
B::somemethod()
不能用B
对象/指针/引用调用。现在只能使用A
的指针或引用来调用它。事实上,我发现有时这种限制是故意引入的。这种情况是当
B 类
的开发人员想要传达这样的消息时,somemethod()
只能使用基类仅多态调用处理。There is no drawback with this approach. The only limitation is that
B::somemethod()
cannot be called withB
object/pointer/reference. It can be now invoked only usingA
's pointer or reference.In fact, I have seen that sometimes this limitation is introduced intentionally. Such scenarios are when the developer of
class B
wants to convey the message that,somemethod()
is meant to be called only polymorphically using base class handle.没有缺点。
但这样做并没有真正的优势。
您仍然可以通过指向案例类的指针访问
somemethod()
。所以在技术方面没有缺点也没有优势。
现在我们来看看使用对象是多么容易。这里有一个缺点,因为您会让对象的用户感到困惑(为什么它在此级别受到保护,而不是较低级别)?因此,您正在为自己创造工作,记录您做出此决定的原因以及您试图通过使用此技术实现的目标。
你真正想要实现的目标是什么?
No drawback.
But no real advantage to do this.
You still have accesses to
somemethod()
via a pointer to the case class.So no drawback and no advantages on the technical side.
So now we move onto how easy it is to use you object. Here there is a downside as you are confusing the user of the object (why is it protected at this level but not the lower level)? So you are creating work for yourself in documenting why you made this decision and what you are trying to achieve by using this technique.
What is it that you really trying to achieve?