【发布时间】:2021-07-22 02:46:49
【问题描述】:
我最近学习了 C++,但我在某些方面遇到了问题,因为我习惯了 Java,而且我不确定我是否以正确的方式做事。
我有一个文本文件,其中行的结构是这样的
C;101;1;1;4;10;
H;102;9;0;1;8;2
C;103;9;9;2;5;
C;104;0;9;3;8;
;是分隔符
C 用于检查是否为 Crawler(H 用于检查是否为 Hopper),然后是 id、position、directions(1-4)、size 和 alive(0/1) )
我有一个抽象的 Bug 类,然后我有一个 Crawler 和 Hopper 类,它们都继承自 Bug 类。
这是我的 Bug 类
class Bug
{
public:
int id;
pair<int, int> position;
int direction;
int size;
bool alive;
list<pair<int, int>> path;
virtual void move() {}
bool isWayBlocked() {}
Bug(string type, int id, pair <int, int> position, int direction, int size, bool alive)
{
type = type;
id = id;
position = position;
direction = direction;
size = size;
alive = alive;
};
};
这里是爬虫类
class Crawler : public Bug
{
public:
Crawler(int id, pair <int, int> position, int direction, int size)
: Bug("Crawler", id, position, direction, size, alive)
{
}
};
这是我尝试创建 Crawler 对象实例的示例:
Bug* bugPtr;
if (bugType == "C") {
bugPtr = new Crawler(bugID, { xPos,yPos }, direction, size);
//Crawler* CrawlerBugPointer = new Crawler(bugID, { xPos,yPos }, direction, size);
}
我能够轻松地从文本文件中读取并存储变量,但是当我开始调试 bugPtr 中的所有字段时说 0,我怀疑我以完全错误的方式处理事情并且没有构建抽象类和继承类正确,谁能指出我做错了什么?任何帮助将不胜感激。
【问题讨论】:
-
type = type;= 你需要了解变量阴影和constructor lists。
标签: c++ class inheritance constructor abstract-class