c++ - 无法在 C++ 中访问派生类的函数

标签 c++ oop inheritance

我正在尝试从我的基类 的对象访问派生类 的方法。我有一个基类 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 对象。

我面临的问题是,在创建对象后,当我尝试访问 myfunctypefunc 时,我得到了编译错误。我如何访问这些函数(我不想在基类中创建这些函数)?

编辑:

我得到的错误是,

  1. 'myfunc' : 不是'CBase'的成员
  2. '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/

相关文章:

java - 没有确定主要方法?

c++ - 在访问者模式中检索类模板的类型

c++ - 使用 `for(auto& e : cont)` 安全吗? vector<bool> 有什么问题?

javascript - 子类化 JavaScript 数组 - 构造函数参数未传递给数组

java - 设置传递参数到基类的可接受的方法是什么?

oop - 如何将一个类的 itcl 对象传递给另一个类的对象并使用所传递对象的功能?

asp.net - 继承一个类以删除属性并更改方法逻辑

c++ - 从 struct 打印 char 指针时出现奇怪的输出

c++ - 匹配里面没有连字符的单词

c++ - “myV”没有命名类型