在功能中设置对象变量

setting object variables inside function

本文关键字:对象 变量 设置 功能      更新时间:2023-10-16

我一直在尝试在外部功能中设置类的变量;我认为这在功能退出后最终会删除课程,如果这是真的,那么如何解决?

Book bookArray[lineIndex];    
bookArray[0].setTitle("Here!");
//function in loop called in main
for (int i = 0; i<lineIndex; i++)
{
    arrayToBook(tempArray, bookArray[i]);
}
cout << bookArray[0].getTitle() << endl;
//returns empty space
//function definition
void arrayToBook(string* tempArray, Book bookIn)
{
    bookIn.setTitle(tempArray[0]);
    bookIn.setAuthor(tempArray[1]);
    //other sets
}

作为评论中的状态,您应该通过(non const(参考:

通过参数
void arrayToBook(const string* tempArray, Book& bookIn)
{
    bookIn.setTitle(tempArray[0]);
    bookIn.setAuthor(tempArray[1]);
    //other sets
}

否则您只修改了一个新副本。