C ++为什么我可以从派生类调用基类的私有虚函数?

时间:2013-04-03 21:01:02

标签: c++ function inheritance virtual private

Herb Sutter的着名文章Virtuality陈述如下:

  

指南#2:更喜欢将虚拟功能设为私有

     

这很容易。这允许派生类重写函数   根据需要自定义行为,而无需进一步公开虚拟   通过使派生类可调用它们直接起作用(如   如果功能只是受到保护,那将是可能的)

在下面的代码中,private_base_func()是在基类中声明的私有虚函数,并在驱动的类构造函数中调用,奇怪的是,这段代码编译得很好,并且从驱动程序调用基类的私有虚函数上课,与上述陈述相矛盾。这让我很困惑。

class base
{
public:

    base() {}
    virtual ~base(){}

private:
    virtual void private_base_func() 
    { 
        std::cout << "Base Class invoke" << std::endl;
    }

};


class drived : public base
{
public:
    drived()
    {
        private_base_func(); // this line should not compile
    }

private:
    // Overriding base class virtual function
    void private_base_func() 
    { 
        std::cout << "Drived class invoke" << std::endl;
    }
};

int main()
{
   base* ptr = new drived();
   return 0;
}

感谢您的回复,

2 个答案:

答案 0 :(得分:8)

那是因为您正在调用drived的{​​{1}}版本,当然可以在private_base_func内访问。您无法调用的函数是drived的版本:

base

答案 1 :(得分:1)

    private_base_func(); // this line should not compile

怎么样? private_base_funcprivate中的drived函数,该行位于drived内,因此调用它是完全正常的。请注意,这与:

不同
drived()
{
    base b;
    b.private_base_func(); // this line does not compile
}

无论如何,这不是文章的内容。本文的重点是基类中定义了两个不同的接口。一个是公共界面,它提供基础用户所需的操作。另一个是虚函数集,它定义了扩展为基类提供的操作。通过分离两个接口,您可以将用户与提供商分离,并获得灵活性。

相关问题