【发布时间】:2021-04-15 12:38:27
【问题描述】:
我正在制作一个包含大量代码的项目,这是我无法将其全部发布的原因之一。 我创建了几个类,其中一些是彼此的朋友。现在,该项目的一个选项是能够创建多种类型的地形,然后将对象插入到“Continente”类的矢量上,它通过下面的循环来实现。
if(linhacomando[1] == "planicie"){
for(int Ploop = 0; Ploop < quantidade; Ploop++){
Planicie P;
C->AddPlanicie(&P);
}
///more types of terrain with further "ifs" below, but posting it all would be too extensive
所以根据我的理解,它创建了一个对象 Planicie,它就是这个类。
class Planicie{
private:
string NomeP;
const int ResistenciaP = 5;
int CriarProdutoP;
const int CriarOuroP = 1;
const int PontosVitoriaP = 1;
int ConquistadoP;
public:
friend class Continente;
friend class Imperio;
friend class Mundo;
static int NPlanicie;
Planicie();
};
还有这个构造函数
int Planicie::NPlanicie = 0;
Planicie::Planicie(){
NPlanicie++;
NomeP = "Planicie" + to_string(NPlanicie);
CriarProdutoP = 1;
ConquistadoP = 0;
cout << NomeP << " criado." << endl;
}
然后它告诉上面创建的对象“C”(在此处发布的代码之外)将刚刚创建的这个对象添加到 C 使用此函数的向量中。
void Continente::AddPlanicie(Planicie * P){
VPlanicie.push_back(P);
}
Continente (C) 是此类
class Continente{
private:
vector <Planicie*> VPlanicie;
vector <Montanha*> VMontanha;
vector <Fortaleza*> VFortaleza;
vector <Mina*> VMina;
vector <Duna*> VDuna;
vector <Castelo*> VCastelo;
public:
friend class Mundo;
void AddPlanicie(Planicie * P);
void AddMontanha(Montanha *M);
void AddFortaleza(Fortaleza *F);
void AddMina(Mina *M);
void AddDuna(Duna *D);
void AddCastelo(Castelo *C);
void ShowContinente();
};
我的问题如下:我现在有一个命令,允许程序显示到目前为止创建的每个地形,这个地形存储在 Continente 的相应向量中,但它不起作用。它编译得很好,完全没有错误,然后我启动它,我也可以很好地创建地形,当我输入命令显示到目前为止已经创建的内容时,它就关闭了。这是代码。
void Continente::ShowContinente(){
for(int loop = 0; loop < this->VPlanicie.size(); loop++){
cout << this->VPlanicie[loop]->NomeP << endl;
}
} /// at this moment I'm trying to only show all Planicie Terrains made so far, kinda like a test before adding the rest.
这是 main 中调用的函数
void Lista(Continente * C){
C->ShowContinente();
}
例如,假设我创建了 3 个 Planicie 对象。它应该让它们位于 VPlanicie 向量的 [0][1][2] 处,然后当我要求它向我展示时,它应该打印 Planicie1、Planicie2、Planicie3。
我知道这是一个广泛的问题,可能令人困惑,但我希望得到一些帮助。
【问题讨论】:
-
某处可能存在未定义的行为。是时候使用调试器了。
-
Planicie P; C->AddPlanicie(&P);你存储局部变量的地址。你得到悬空指针和 UB 随之而来。 -
@churill 因为它是一个对象,它无论如何都可以工作吗?因为我正在创建对象并将指向它们引用的指针存储在向量中?
-
@user215272 创建对象,存储指向它的指针,然后销毁对象。现在指针没有指向任何东西。