用C ++创建类列表

时间:2014-04-29 18:30:45

标签: c++ class

我有班级船:

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

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

Ship **list;

并在Side类的构造函数中:

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。

1 个答案:

答案 0 :(得分:1)

如果不讨论您的方法的设计,代码可以采用以下方式

#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>而不是动态分配的数组和动态分配的对象,那么毫无疑问会更好。