gpt4 book ai didi

c++ - 由于复制构造函数,vector .pushback 方法未将类对象插入 vector

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:23 26 4
gpt4 key购买 nike

我有一个 cashier 类,它有 3 个属性:IDPasswordtries,使用标准 GET & 设置方法

//Header file

#ifndef CASHIER_H
#define CASHIER_H
#include <string>
using namespace std;


class cashier
{
public:
cashier();
cashier(const cashier& orig);
virtual ~cashier();

void setID(string);
string getID();

void setPassword(string);
string getPassword();

void settries(int);
int gettries();

private:
string ID;
string Password;
int tries;



};

#endif /* CASHIER_H */

收银员.cpp文件

#include "cashier.h"

cashier::cashier()
{

}

cashier::cashier(const cashier& orig)
{

}

cashier::~cashier()
{

}

void cashier::setID(string value)
{
this->ID = value;
}

void cashier::setPassword(string value)
{
this->Password = value;
}

string cashier::getID()
{
return this->ID;
}

string cashier::getPassword()
{
return this->Password;
}

void cashier::settries(int value)
{
this->tries=value;
}
int cashier::gettries()
{
return this->tries;
}

在我的主文件中,我试图从文本文件中读取并将值存储在 cashier c 中并将其推送到我的 vector cashier_all

#include <iostream>
#include "cashier.h"
#include <fstream>
#include <vector>
int main()
{

fstream afile;
char rubbish[100];

afile.open("cashier.txt",ios::in);

afile.getline(rubbish,100); //read in first line

vector <cashier> cashier_all;

cashier c;
string temp_id;
string temp_password;
int temp_tries;


while(afile>>temp_id)
{
afile>>temp_password;

afile>>temp_tries;

c.setID(temp_id);
c.setPassword(temp_password);
c.settries(temp_tries);

cashier_all.push_back(c); //c is not being pushed into the vector
// for some unknown reason


}

vector<cashier>::iterator v1;
vector<cashier>::iterator v2;
v1 = cashier_all.begin();
v2 = cashier_all.end();

while (v1 != v2)
{
cout<<v1->getID()
<<endl
<<v1->getPassword()
<<endl
<<v1->gettries();
v1++;


}

system("PAUSE");

}

收银台.txt

CashierID               password        tries
001 def 0
002 ghi 0
003 jkl 0

检查我的调试器,错误出在 cashier_all.pushback 那里它没有将 c 插入 vector cashier_all,如果你不相信我,你可以自己尝试

编辑:它在我删除所有构造函数后起作用

我不明白为什么复制构造函数会影响将 cashier 插入 cashier_all ,有人可以向我解释一下吗??

最佳答案

摆脱生成方法的不必要实现,例如,您的复制构造函数:照原样,您的复制构造函数与默认构造函数的作用相同。但是,它应该复制该对象。删除它会产生一个复制构造函数,它就是这样做的。作为额外的好处,编译器还会为您生成移动构造函数。

当将对象插入到容器中时,对象被复制(如果它是临时对象则移动):C++ 基于,而不是引用!

关于c++ - 由于复制构造函数,vector .pushback 方法未将类对象插入 vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com