我的setter能取到参数,居然取不到?

My setter can get parameters,but actually can't?

所以我正在制作某种注册表来存储人们的信息。 我的问题是我有一个 class,其中有多个 setter 和 getter 用于一个人(名字、出生日期、出生地等)。 当我尝试从文本文件中读取信息时,我无法向 setters 提供我从文件中获得的参数。

我制作了一个草稿文件,试图找出问题所在,但我真的找不到任何地方。循环无所谓,如果我想做的事情不在循环中并且文件中只有一行,问题仍然存在

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

都可以正常工作

这就是我的 setter 和 getter 在我的通讯录中的样子 class

    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 的代码中。你没有提供。请提供 Minimal, Complete, and Verifiable example