首页 > 解决方案 > C ++跨类访问基对象向量中的派生对象的引用

问题描述

我正在尝试创建一个存储基类的向量,然后将其传递给另一个类,然后从基类的向量访问派生类我发现了多个涵盖此问题的 Stack Overflow 问题,但它们都缺少某些方面,例如传递跨类或将多个对象存储在一个向量中。CPP 文件

vector<Item*> Items::cM() {
    vector<Item*> M;
    string line;
    string filePath = "...";
    ifstream stream(filePath);
    while (getline(stream, line)) {
        vector <string> IV= UtilFunctions::splitString(line, ',');
        const char *t= IV[0].c_str();
        switch (*t) {
        case 'a': {
            StarterFood tmpStarter = StarterFood(*a,b,c);//Simplified
            Item* b = &tmpStarter;
            M.push_back(b);
            //If I use b here and do b->toString() works as expected
            break;
        }
        
        }
        
    }
    return M;
}

主要的

int main(){
    vector <Item*> i= Items::cM();
    items[0]->toString();//This is an overloaded function that all of the derived classes 
    //Throws the error Access violation reading location 0xCCCCCCCC.
    have such as starterfood
    system("pause");
    return 0;
}

如果需要更多信息,请随时询问。谢谢我也尝试过传递一个指针,然后取消引用该指针,但我认为切片我的对象只留下基类,我尝试实现 unique_ptr 但我收到一个语法错误,说没有从 starterFood 返回 unique_ptr 的重载。错误是访问冲突读取位置 0xCCCCCCCC。

标签: c++ooppointersderived-classbase-class

解决方案


正如我建议的那样,我使用了 unique_ptr 我必须在派生类上使用 make_unique 并在存储在向量中时移入派生类并将所有 vector<Item*> 替换为 vector<unique_ptr> 但它现在可以工作了。

vector<unique_ptr<Item>> Items::cM() {
    vector<unique_ptr<Item>> M;
    string line;
    string filePath = "...";
    ifstream stream(filePath);
    while (getline(stream, line)) {
        vector <string> IV= UtilFunctions::splitString(line, ',');
        const char *t= IV[0].c_str();
        switch (*t) {
        case 'a': {
            unique_ptr<StarterFood> tmpStarter = make_unique<StarterFood> 
            (*a,b,c);
            M.push_back(std::move(tmpStarter));
            break;
        }
        
        }
        
    }
    return M;
}

然后在主

    vector<unique_ptr<Item>> i= Items::cM();
    items[0]->toString();//This is an overloaded function that all of the 
    derived classes
    system("pause");
    return 0;

这解决了我最初尝试的对象切片问题。


推荐阅读