假设我们有一个来自抽象基类的派生类.指向抽象基类的指针在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;
}
解决方法:
厚脸皮的回答:不要.我的意思是,如果你真的需要,你的技术问题的答案是C中的dynamic_cast操作,以便进行“向下转换”(从基础转换为派生类).
但退一步,这是虚拟功能的合理用例.问问自己,我想要访问的常见含义是什么?
在这种情况下,我们希望所有学生都有一个识别号码.
工作源代码:http://ideone.com/5E9d5I
class clsStudent
{
public:
virtual void display() = 0;// {cout<<"Student\n";}
virtual void identifyingNumber() = 0;
};
class clsInternational : public clsStudent
{
public:
void display(){cout<<"International\n";}
void identifyingNumber(){cout<<"Pass\n";}
};
class local : public clsStudent
{
public:
void display(){cout<<"Local\n";}
void identifyingNumber(){cout<<"IC\n";}
};
int main()
{
clsStudent * s = new clsInternational;
clsStudent * s2 = new local;
s->display();
s->identifyingNumber();
s2->display();
s2->identifyingNumber();
return 0;
}