在C++中创建类列表
Create list of classes in C++
我有类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>
而不是动态分配的数组和动态分配的对象,那会更好。
相关文章:
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 在c++中为链接列表创建复制构造函数/函数
- C++类型列表创建子列表
- 使用初始值设定项列表创建单个项向量
- 如何在C 类中使用备用参数列表创建和使用finturePointer
- C++:从两个包含子类 (typedef) 的列表创建一个列表
- 在线性时间内使用邻接列表创建对顶点
- 从类型列表创建向量元组
- C 链接列表创建链接列表的链接列表
- 需要一个宏来从 std::ostringstream 和 << arg 列表创建 std::string
- 从 2D C 列表创建 boost.geometry.model.polygon
- 如何在C++中使用 STL 列表创建循环
- 使用Templates从参数列表创建std::vector
- 链接列表创建节点
- 如何从 CGAL 中的坐标和拓扑列表创建Polyhedron_3数据结构
- 是否可以使用初始值设定项列表创建临时结构/类
- 如何通过子类型列表创建指针向量
- 为双链接列表创建类的新实例
- 如何用集合顶点列表创建boost子图
- 是否可以为通用元素列表创建排序