push_back通过自行创建的对象获取最后一个元素的向量
push_back getting a vector of last element by self created object
我正在尝试阅读动物列表,这工作正常。然后我想将每个字符串分成两个子字符串,用于name
和cmc
,这也很好用。但是我的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
。
相关文章:
- 如何在C++中获取该对象的类声明中对象的地址?
- 无法获取webot::PositionSensor对象中位置传感器的值
- 最多获取2个对象
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 如何在新的派生对象中获取基本对象的数据?
- 如何从 CSV 获取数据并将其存储在 C++ 中的表对象中
- 数组中不同类型的对象并获取每个对象的类型
- push_back通过自行创建的对象获取最后一个元素的向量
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 在C++中从内部类对象获取外部类对象
- 如何从 GDI+ 图元文件对象获取原始图元文件字节
- C++ std::队列推送弹出两个不同的对象获取第一个对象
- 尝试从另一个类对象获取值时出现分段错误
- 从元对象获取属性更改通知程序
- 从 Json 对象获取非缩进字符串
- 从套接字对象获取fd或句柄
- (如何)我可以从IWbemClassObject对象获取GUID吗
- 使用不同类中的类对象获取不正确的数据
- OpenCV Mat 对象 - 获取数据长度
- 在 c++ 中,如何从对象获取到静态成员