我可以调用从main()重写的虚函数吗?

问题描述 投票:2回答:1

我知道


// C++ program for function overriding 

#include <bits/stdc++.h> 
using namespace std; 

class base 
{ 
public: 
    virtual void print () 
    { cout<< "print base class" <<endl; } 

    void show () 
    { cout<< "show base class" <<endl; } 
}; 

class derived:public base 
{ 
public: 
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly 
    { cout<< "print derived class" <<endl; } 

    void show () 
    { cout<< "show derived class" <<endl; } 
}; 

//main function 
int main()  
{ 
    base *bptr; 
    derived d; 
    bptr = &d; 

    //virtual function, binded at runtime (Runtime polymorphism) 
    bptr->print();  

    // Non-virtual function, binded at compile time 
    bptr->show();  

    return 0; 
} 

我可以打印

print derived class
show base class
show derived class

我可以打印

print base class

仅通过更改d而没有创建另一个对象的派生类的对象main()?如果是,如何?

c++ polymorphism virtual-functions
1个回答
9
投票

我可以仅通过更改d来使用派生类的对象main()打印打印基类>

是,可以。您必须在调用中显式使用基类。

bptr->base::print();  

您也可以直接使用d

d.base::print();  
© www.soinside.com 2019 - 2024. All rights reserved.