push_back通过自行创建的对象获取最后一个元素的向量

push_back getting a vector of last element by self created object

本文关键字:对象 获取 最后一个 向量 元素 创建 back push      更新时间:2023-10-16

我正在尝试阅读动物列表,这工作正常。然后我想将每个字符串分成两个子字符串,用于namecmc,这也很好用。但是我的cout不起作用。

例如,我的animal.txt是:

狗|嗨 猫|苗 cow|hihi

我的for循环输出应如下所示:

狗 猫 牛

但实际输出是:

牛 牛 牛

这是我的Animal.cpp

#include <string>;
#include <vector>;
#include <fstream>;
#include "Animal.h"
using namespace std;
string cmc;
string name;
void Animal();
void Animal(string nameA) {
name = nameA;
}
void Animal(string nameA, string cmcValue) {
name = nameCard;
cmc = cmcValue;
}
void Animal::setName(string names)
{
name = names;
}
void Animal::setCmc(string cmcvalue) {
cmc = cmcvalue;
}
std::string Animal::getName() {
return name;
}
std::string Animal::getCmc() {
return cmc;
}
void Animal::openfileAnimal() {
ifstream inFileAnimal;
inFileAnimal.open("Animals.txt");
if (inFileAnimal.fail()) {
cerr << "error open this file" << endl;
exit(1);
}
string itemsAnimal;
std::vector<Animal> AllAnimals;
while (getline(inFileAnimal, itemsAnimal)) {
Animal c;
string t1 = itemAnimal;
size_t pos = t1.find("|");
//name (setname(sub))
string sub = t1.substr(0, pos);
c.setName(sub);
string t2 = t1.substr(sub1.length() + 1, t1.length());
string sub2 = t2.substr(0, t2.length());
c.setCmc(sub2);
AllAnimals.push_back(c);
}
for (int i = 0; i < 2; i++) {
std::cout <<AllAnimals.at(i).getName() << endl;
}
}

我读过其他像我这样的 StackOverflow 问题,但对于我的例子,所有解决方案都不起作用。那么我的问题在哪里?我想这就像我一遍又一遍地修改相同的内存。

您有全局变量而不是类数据成员:

string cmc;
string name;
void Animal();
void Animal(string nameA) {
name = nameA;
}
void Animal(string nameA, string cmcValue) {
name = nameCard;
cmc = cmcValue;
}

因此,您只保留最新分配的值。此外,您可能将其视为构造函数的东西根本不是构造函数。构造函数应如下所示:

Animal::Animal(string nameA, string cmcValue)
: name(nameA), cmc(cmcValue) {
}

请注意,初始化列表语法:这样可以避免像您的错误一样的错误。

顺便说一下,在您的代码中根本没有定义nameCard