的对象访问基类的受保护成员函数我们有两个类:Base和Derived。在名为PrintValue()的基类中有一个函数,它已被定义为受保护的。派生类从Base类继承此函数,但它可以通过在公开部分中声明它来将其访问说明符更改为public。我的问题是:这是一个很好的软件工程实践吗?为什么Derived类继承了Base类的一个函数,能够将该函数的访问级别更改为public,该类已经被Base类声明为protected。这样,在主函数中,可以声明Derived类的对象并访问Base类的受保护函数,这违背了Base类的期望。C++使用派生类
class Base
{
private:
int m_nValue;
public:
Base(int nValue)
: m_nValue(nValue)
{
}
protected:
void PrintValue() { cout << m_nValue; }
};
class Derived: public Base
{
public:
Derived(int nValue)
: Base(nValue)
{
}
// Base::PrintValue was inherited as protected, so the public has no access
// But we're changing it to public by declaring it in the public section
Base::PrintValue;
};
int main()
{
Derived cDerived(7);
// PrintValue is public in Derived, so this is okay
cDerived.PrintValue(); // prints 7
return 0;
}
谢谢你的回答。所以我得到的是Base类不能盲目地信任Derived类,并假设任何东西都将它作为受保护留在它们之间。实际上我并没有期望派生类具备这种能力,特别是基于我以前的公有继承经验,即所有成员保持其原始访问规范。私人会员保持私密,受保护的会员保持受保护,公共会员保持公开。 – 2014-09-04 19:18:29