gpt4 book ai didi

c++ - 我将如何在 C++ 中实现动态绑定(bind)的这种使用?

转载 作者:行者123 更新时间:2023-11-28 00:23:56 25 4
gpt4 key购买 nike

我已经尝试了很多事情并思考了一段时间,但我就是想不出正确的语法/逻辑。

我有一个基类和两个派生类。我正在使用动态绑定(bind)制作一个存储所有 3 个类实例的 vector 。然后,我从文件中读取,它指定它属于哪个类(我将使用 if 语句检查文件中的字符串,例如“base”、“der1”、“der2”)。然后它将其压入堆栈。

如果每个类只有一个,我可以管理以上内容,但是,每个类都有多个。因此,类似下面的代码将不起作用:

vector<Base*> myVec;

然后:

Base *b = new Base;
Der1 *d1 = new Der1;
Der2 *d2 = new Der2;

//read the file and fill in the classes data members

myVec.push_back(b);
myVec.push_back(d1);
myVec.push_back(d2);

上面的代码只会阅读每种类型的类(class)一次,然后继续进行。我将如何实现以下内容:

for(int i = 0; i < lines; i++) //lines = how many lines in file
{
cin.get(whatType, ':'); //reads a string up to the delim char :

if(whatType == "Base")
{
//read line and fill rest of data members...
myVec.push_back(b);
}
else if(whatType == "Der1")
{
//read line and fill rest of data members...
myVec.push_back(d1);
}
if(whatType == "Der2")
{
//read line and fill rest of data members...
myVec.push_back(d2);
}
}

但是,当再次读入相同的类类型时,前一个会被覆盖,而且它是指向一个实例的指针?所以最后输出是不正确的。我希望它们都是唯一的实例。

我该怎么做?我不知道。

最佳答案

您应该每次都创建类的新实例,如下所示:

    vector<Base*> myVec;

// main loop
for (int i = 0; i < lines; i++) //lines = how many lines in file
{
cin.get(whatType, ':'); //reads a string up to the delim char :

if(whatType == "Base")
{
Base *b = new Base;
//read line and fill rest of data members...
myVec.push_back(b);
}
else if(whatType == "Der1")
{
Der1 *d1 = new Der1;
//read line and fill rest of data members...
myVec.push_back(d1);
}
if(whatType == "Der2")
{
Der2 *d2 = new Der2;
//read line and fill rest of data members...
myVec.push_back(d2);
}
}

// deleting pointers
for (int i = 0; i < myVec.size(); ++i)
{
delete myVec[i];
}

关于c++ - 我将如何在 C++ 中实现动态绑定(bind)的这种使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com