gpt4 book ai didi

c++ - 将临时对象分配给调用对象

转载 作者:行者123 更新时间:2023-11-28 00:41:18 24 4
gpt4 key购买 nike

我正在做书中的练习。我有一个类(名为 Golf),它的一个函数应该将一些数据传递给构造函数以创建一个临时对象,并将该临时对象分配给调用对象,即 *this。这是代码:

Golf::Golf(const std::string name, int hc)
{
fullname = name;
handicap = hc;
}

int Golf::setgolf()
{
std::string name;
std::cout << "Enter the name: ";
std::getline(std::cin, name);
std::cin.clear();
std::cin.sync();
if (name == "")
return 0;
else
{
int handicap;
std::cout << "Enter the handicap: ";
std::cin >> handicap;
*this = Golf(fullname, handicap); //this line doesn't set the values
return 1;
}
}

但它不起作用。我还没有在互联网上找到任何解决方案。我应该怎么做?

最佳答案

*this = Golf(fullname, handicap);

这将从当前对象的 fullname 字段初始化临时对象的 fullname不是 从刚刚从输入中读取的名称。你可能想要:

*this = Golf(name, handicap);

或者,您可以重命名局部变量以隐藏成员,尽管有些人不赞成这种做法。

关于c++ - 将临时对象分配给调用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18741557/

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