假设我们有一个来自抽象基类的派生类.指向抽象基类的指针在main中声明,并通过"new"分配给派生类.如何从指向基类的指针(而不是派生类的对象)访问派生类的成员函数?
例:
#include <iostream>
using namespace std;
class clsStudent
{
public:
virtual void display() = 0;// {cout<<"Student\n";}
};
class clsInternational : public clsStudent
{
public:
void display(){cout<<"International\n";}
void passportNo(){cout<<"Pass\n";}
};
class local : public clsStudent
{
public:
void display(){cout<<"International\n";}
void icNo(){cout<<"IC\n";}
};
int main()
{
clsStudent * s = new clsInternational;
clsStudent * s2 = new local;
s->display();
s->passportNo(); //This won't work
return 0;
}
Run Code Online (Sandbox Code Playgroud)