我写了下面的代码。
#include <iostream>
using namespace std;
class CI
{
public:
virtual void display() =0;
};
class Inter: public CI
{
public:
int parseData (int);
};
Inter::parseData (int data)
{
cout <<"Parsing the data "<<data;
return data*100;
}
class Last: public Inter
{
public:
void display();
};
void Last::display()
{
cout <<" Last:: Displaying From Last "<<endl;
}
class USB: public Inter
{
public:
void display();
};
void USB::display()
{
cout <<" USB:: Displaying From Last "<<endl;
}
int main ( int argc, char ** argv)
{
int temp;
CI *obj = new Last;
obj->display();
temp = obj->parseData (100);
cout <<"Parsed DAta .. "<<temp<<endl;
delete obj;
obj = new USB;
obj->display();
temp = obj->parseData (200);
}
我的问题是:
为什么我无法调用 obj->parseData 函数?。根据我的理解,因此类“Last”和“USB”派生自类“Inter”,它应该是可调用的,对吗?..
请告诉我我的理解哪里不对?
最佳答案
obj
必须声明为 Last *
,或者至少是 Inter *
Inter *obj = new Last;
或
Last *obj = new Last;
如果obj
只是一个CI *
,编译器看不到parseData()
方法(你的对象被实例化为Last , 但立即隐式转换为 CI 并失去了该方法的好处)。
我建议您寻找upcast
的概念是什么意思。 (另请参阅关于隐式转换
here 或其他)...
关于c++ - 多层次抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17083103/