我正在尝试从我的基类 的对象访问派生类 的方法。我有一个基类 CBase
,它是一个抽象类,
class CBase{
protected:
char path[255];
public:
virtual void StartBackup()=0;
void setpath(char * path)
{
strcpy(this->path,path);
}
virtual void afunc()
{
printf("Base\n");
}
};
现在Ctype1和Ctype2这两个类是CBase的派生类
class CType1:public CBase{
public:
void StartBackup()
{
printf("Type1:%s",path);
}
void afunc()
{
printf("CType1:afunc\n");
}
void myfunc()
{
printf("myfunc\n");
}
};
class CType2:public CBase{
public:
void StartBackup()
{
printf("Type2:%s",path);
}
void afunc()
{
printf("type2:afunc\n");
}
void typefunc()
{
printf("typefunc\n");
}
};
我有一个 CManager 类,它有一个 CBase 类的对象作为它的成员,
class CManager{
private:
CBase * obj;
public:
CManager(){
obj = NULL;
}
~CManager(){
if(obj)
delete obj;
obj = NULL;
}
void inittype(int type)
{
if(type == 1)
{
obj = new CType1();
obj->myfunc();
}
else
{
obj = new CType2();
obj->typefunc();
}
}
};
在 void inittype(int type)
函数中,我将输入作为类型并相应地初始化 CBase 对象。
我面临的问题是,在创建对象后,当我尝试访问 myfunc
或 typefunc
时,我得到了编译错误。我如何访问这些函数(我不想在基类中创建这些函数)?
编辑:
我得到的错误是,
- 'myfunc' : 不是'CBase'的成员
- 'typefunc' : 不是'CBase'的成员
谢谢
最佳答案
如果您只需要在创建时访问类的非派生函数,那么这就可以了
void inittype(int type)
{
if(type == 1)
{
CType1* temp = new CType1();
temp->myfunc();
obj = temp;
}
else
{
CType2* temp = new CType2();
temp ->typefunc();
obj = temp;
}
}
如果您需要在其他时间访问这些成员函数,则需要使用强制转换 - 例如
CType2* child = dynamic_cast<CType2*>(obj);
关于c++ - 无法在 C++ 中访问派生类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19704214/