在C++中创建类列表

Create list of classes in C++

本文关键字:列表 创建 C++      更新时间:2023-10-16

我有类Ship:

class Ship {
    protected:
        int x, y;
        string type;
    public:
        Ship(string);
        void addCoordinates(int, int);
};

在另一个类Side中,我想列出船只的列表,并添加所有船只的坐标在Side类中,我创建了一个私有变量:

Ship **list;

和在建造师的边类:

list = new Ship*[BufferSize];

现在,我得到了船型和坐标的文件:

A 3 2
B 4 5
C 7 3

等等。

在我的循环中,如何创建Ship对象并向该对象添加坐标

我的每个循环的变量:

string type = list[0]
int x = list[2]
int y = list [4]

Ship对象的构造函数正在获取船舶类型并将其分配给类型变量,addCoordinates函数接受2个整数并将它们分配给x和y。

如果不讨论方法的设计,代码可能看起来像

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
//...
std::string record;
size_t i = 0;
while ( i < BufferSize && std::getline( FileStream, record ) )
{
   if ( record.find_first_not_of( " t" ) == std::string::npos ) continue;
   std::istringstream is( record );
   std::string type;
   is >> type;
   list[i] = new Ship( type );
   int x = 0, y = 0;
   is >> x >> y;
   list[i]->addCoordinates( x, y );
   ++i;
}

毫无疑问,如果使用std::vector<Ship>而不是动态分配的数组和动态分配的对象,那会更好。