我可以调用从 main() 覆盖的虚函数吗?
Can I call a virtual function that is overridden from main()?
我知道这个
// 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
使用派生 class 的对象 d
仅更改 main()
而无需创建另一个对象?如果是怎么办?
can I print print base class with the object d
of the derived class with just changing main()
是的,你可以。您必须在调用中明确使用基数 class。
bptr->base::print();
也可以直接使用d
。
d.base::print();
我知道这个
// 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
使用派生 class 的对象 d
仅更改 main()
而无需创建另一个对象?如果是怎么办?
can I print print base class with the object
d
of the derived class with just changingmain()
是的,你可以。您必须在调用中明确使用基数 class。
bptr->base::print();
也可以直接使用d
。
d.base::print();