c++ - 我的设置器可以获取参数,但实际上不能?
问题描述
所以我正在制作某种存储人们信息的注册表。我的问题是我有一个类,它有一个人的多个 setter 和 getter(名字、出生日期、出生地等)。当我尝试从文本文件中读取信息时,我无法为设置器提供从文件中获取的参数。
我制作了一个临时文件,试图找出问题所在,但我真的无处可去。循环无关紧要,如果我想做的事情不在循环中并且文件中只有一行,那么问题仍然存在
int main(){
std::string firstName;
std::string lastName;
std::string phoneNumber;
std::string birthPlace;
std::string birthDate;
std::string Profession;
Contacts newContact = Contacts();
std::ifstream savedContacts("ContactList.txt");
do{
std::getline(savedContacts, firstName, ';');
std::getline(savedContacts, lastName, ';');
std::getline(savedContacts, phoneNumber, ';');
std::getline(savedContacts, birthPlace, ';');
std::getline(savedContacts, birthDate, ';');
std::getline(savedContacts, Profession, ';');
/*
in this case, this setter doesn't work,
it doesn't get the string stored in firstName,after this,the program
crashes
*/
newContact.setFirstname(firstName);
std::cout<<newContact.getFirstname();
/*
and just to make sure that the reading of the file was successful
if i print out one of these strings, like this, it works perfectly
*/
std::cout<<firstName;
}while(std::getline(savedContacts, firstName));
有趣的是,如果我这样做: newContact.setFirstname("Karen"); 然后二传手完美地工作,也是我的吸气剂
这就是我的联系人类中我的 setter 和 getter 的样子
std::string Contacts::setFirstname(std::string firstName) {
this->firstName = firstName;
}
std::string Contacts::getFirstname() {
return firstName;
}
这是在 txt 文件中:
John;Wick;1800181819;Paris;11.09.1990;Plumber;
Anthony;Joshua;192918180;Manchester;10.08.1994;Teacher;
解决方案
// Several issues here:
std::string Contacts::setFirstname(std::string firstName) {
this->firstName = firstName;
}
// Don't return a copy. Setters will usually only *set*
// If you WANT to return the value, you should NOT return a copy
// but a reference or a const reference
// You are copying AGAIN for the argument; take a const reference
// And probably avoid a copy
// Change parameter name and you could spare the this->
// and return a value; you declared a return type but no return statement
// Which means the code you posted doesn't compile
const std::string& Contacts::setFirstname(const std::string& newFirstName)
{
firstName = newFirstName;
return firstName;
}
// Same here, return const reference and let the caller copy only if needed
// And make the getter const so it can work with const Contact
const std::string& Contacts::getFirstname() const {
return firstName;
}
另外,关于您的问题,很可能是在调用 setFirstName 的代码中。你没有提供的。请提供最小、完整和可验证的示例
推荐阅读
- vba - 搜索大量文件并根据搜索字符串将某些行提取到单独的单个文件中
- html - 找出 CSS 行为背后原因的方法
- r - rlang::flatten() 的基本等价物是什么?
- java - 为什么在这种情况下 ExecutorService 返回正确答案 19 次?错误在哪里?
- c++ - ffmpeg:sws_scale 无法将图像从 YUV 转换为 RGB
- ssl-certificate - 将证书签名请求公钥从 ECDSA 转换为 RSA
- jquery - 禁用按钮在 IE 11 中不起作用,但它在 chrome 中起作用
- android - 即使设置环境变量后也无法识别颤振
- ios - 重构我的数组迭代的建议?
- php - 自 PHP 7.2 起不推荐使用函数 read_exif_data()