【问题标题】:C++ Why I can invoke private virtual function of base class from a drived class?C++ 为什么我可以从派生类调用基类的私有虚函数?
【发布时间】:2013-03-25 18:00:12
【问题描述】:

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;
}

提前感谢您的回复

【问题讨论】:

    标签: c++ function inheritance virtual private


    【解决方案1】:

    那是因为您调用的是drivedprivate_base_func 版本,当然可以在drived 中访问。不能调用的函数是base的版本:

    drived()
    {
        base::private_base_func(); // this line will not compile
    }
    

    【讨论】:

      【解决方案2】:
          private_base_func(); // this line should not compile
      

      怎么会? private_base_funcdrived 中的private 函数,并且该行在drived 内,因此调用它非常好。请注意,这不同于:

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

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

      【讨论】:

        猜你喜欢
        • 2016-10-08
        • 1970-01-01
        • 1970-01-01
        • 2013-10-08
        • 2020-04-07
        • 2021-03-08
        • 2018-05-11
        • 2011-09-27
        • 1970-01-01
        相关资源
        最近更新 更多