将私人职能改写为公众的潜在危险是什么?

Rah*_*ahn 5 c++ object-oriented-analysis

我发现在C++中允许将基本对象的私有函数覆盖为公共函数,因为Visual Studio会产生0警告.这样做有潜在的危险吗?

如果没有,在基础对象中声明私有,受保护和公共虚函数之间有什么区别?

Sin*_*all 1

这样做有潜在的危险吗?

我不这么认为,因为你的能力仍然很有限:

class Base
{
private:
    virtual void foo(){}
};

class Derived1 : public Base
{
public:
    virtual void foo(){ Base::foo(); }
};

class Derived2 : public Base
{
public:
    virtual void foo(){}
};

int main()
{
    Derived1 d1;
    d1.foo(); //error
    Base * d2 = new Derived2();
    d2->foo(); //error
}
Run Code Online (Sandbox Code Playgroud)

因此,最多您将能够调用重载函数(如果它不从自身调用基类中的函数),但基类的函数仍将具有相同的可见性,并且将无法访问。

  • `virtual void foo(){ Base::foo(); }` 等等...这真的能编译吗?这里应该有一个错误,不仅在`main()`中,因为`Base::foo()`不能被子类访问...... (3认同)