📜  虚拟函数可以在C++中私有吗?

📅  最后修改于: 2021-05-25 22:50:10             🧑  作者: Mango

在C++中,虚函数可以是私有的,并且可以被派生类覆盖。例如,以下程序可以编译并正常运行。

C++
#include 
 
class base
{
public:
     
    // default base constructor
    base() { std::cout << "base class constructor\n"; }
   
    // virtual base destructor
    // always use virtual base
    // destructors when you know you
    // will inherit this class
    virtual ~base()
    {
        std::cout << "base class destructor\n";
    }
    // public method in base class
    void show()
    {
        std::cout << "show() called on base class\n";
    }
     
    // public virtual function in base class,
    // contents of this function are printed when called
    // with base class object when called with base class
    // pointer contents of derived class are printed on
    // screen
    virtual void print()
    {
        std::cout << "print() called on base class\n";
    }
};
 
class derived : public base {
public:
    // default derived constructor
    derived()
        : base()
    {
        std::cout << "derived class constructor\n";
    }
    // virtual derived destructor
    // always use virtual destructors
    // when inheriting from a
    // base class
    virtual ~derived()
    {
        std::cout << "derived class destructor\n";
    }
 
private:
    // private virtual function in derived class overwrites
    // base class virtual method contents of this function
    // are printed when called with base class pointer or
    // when called with derived class object
    virtual void print()
    {
        std::cout << "print() called on derived class\n";
    }
};
 
int main()
{
    std::cout << "printing with base class pointer\n";
     
    // construct base class pointer with derived class
    // memory
    base* b_ptr = new derived();
     
    // call base class show()
    b_ptr->show();
     
    // call virtual print in base class but it is overridden
    // in derived class also note that print() is private
    // member in derived class, still the contents of derived
    // class are printed this code works because base class
    // defines a public interface and drived class overrides
    // it in its implementation
    b_ptr->print();
 
    delete b_ptr;
}


输出
printing with base class pointer
base class constructor
derived class constructor
show() called on base class
print() called on derived class
derived class destructor
base class destructor

上面的程序中没有什么要注意的。
b_ ptr是基本类型的指针,并指向派生类对象。当调用ptr-> print()时,将执行Derived的print()。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”