我如何在c ++中实现Dynamic Binding的这种用法?

时间:2014-09-26 01:10:28

标签: c++

我一直在尝试多种方法并思考一段时间,但我无法想到它的正确语法/逻辑。

我有一个基类和两个派生类。我正在使用动态绑定来创建一个存储所有3个类的实例的向量。然后,我从一个文件读入,它指定它属于哪个类(我将使用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);

以上内容将只读取每种类型的类,并将它们推上去。我将如何实现以下方面的内容:

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);
    }
}

但是,当再次读入相同的类类型时,前一个类型将被覆盖,并且它是指向一个实例的指针?因此最后输出将是不正确的。我希望他们都是独特的实例。

我该怎么做呢?我不知道。

1 个答案:

答案 0 :(得分:3)

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

    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];
    }