我的二传手可以得到参数,但实际上不可以?

问题描述 投票:-1回答:1

所以我正在制作某种存储人们信息的注册表。我的问题是,我有一个课程,有一个人的多个二传手和吸气剂(名字,出生日期,生活地点等)。当我尝试从文本文件中读取信息时,我无法为设置者提供从文件中获取的参数。

我做了一个临时文件,我试图弄清楚问题,但我真的无法到达任何地方。循环没关系,如果我想要做的事情不在循环中并且文件中只有一行,问题仍然是相同的

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;
c++ oop setter
1个回答
0
投票
// 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的代码中。你没有提供。请提供Minimal, Complete, and Verifiable example

© www.soinside.com 2019 - 2024. All rights reserved.