c++ - 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。
解决方案
正如我建议的那样,我使用了 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;
这解决了我最初尝试的对象切片问题。
推荐阅读
- python - Django 休息框架 | Knox 身份验证密码未在数据库中散列
- spring-data - 在简单的应用程序中使用 Spring Data 获取 Arango 存储库的不满意依赖项
- java - 如何强制子 spring boot jar 从父 spring boot 读取属性
- mysql - 如何在 ORM Symfony 4 中将列的数据类型从 STRING 更改为 TEXT?
- php - PHP:在不区分大小写的情况下获取文件
- javascript - 如何在 xamarin 的 webview 应用程序中从 js 运行 ac# 方法
- odoo-12 - 更改因为删除而出现的错误消息
- swift - Metal:为 MSL cikernel 设置编译器和链接器选项后,.metal 文件中定义的 vertexFunction 变为 nil
- oracle - 即使在授予豁免政策之后,Exchange 子分区也因 VPD 而失败
- javascript - 如果有一些验证,Ctrl+A 在输入框上的 Firefox 中不起作用