我必须创建所需的函数模板提示,它显示提供的字符串,然后返回模板类型的值。最后,添加一行调用此函数的字符串“What is the answer?”(注意尾随空格)并将此答案存储在提供的结构的 misc 字段中。
我不知道我在做什么,请帮忙!
#include
#include
using std::string;
struct Answers {
tên chuỗi;
float answer;
int misc;
};
// write template function "prompt" here
**template
void prompt(string prompt_question, T& answer)
{
prompt_question = "What is the answer? ";
cin >> trả lời;
misc = answer;
}**
// what should I have written?
int main(int argc, char* argv[])
{
**using namespace std;
Answers info {
prompt("What is your name? "),
prompt(argv[2]),
};**
cout << '\n' << "Who: " << info.name;
cout << '\n' << "Knowledge: " << info .answer;
cout << '\n' << "Wisdom: " << info.misc;
trả về 0;
}
我不知道如何解决它,我觉得很愚蠢,从 7 est 开始就一直在努力解决这个问题。请帮忙不幸的是,** 之间的东西是我唯一可以编辑的东西
恕我直言,OP 的尝试并不那么幸运。
我试着整理一下:
template prompt(string prompt_question)
那坏了。缺少函数标识符。或者,可能是缺少函数的返回类型,但函数名称与模板参数的标识符相同。
prompt_question = answer;
?
这有什么用?
trả lời
未在此范围内声明或初始化。
为什么 prompt_question
应该被它覆盖吗?
answer = "What is the answer?
?
这有什么用?
misc = answer;
?
这有什么用?
misc
未在此范围内声明。
我的工作示例展示了它的样子:
#include
#include
struct Answers {
std::string name;
float answer;
int misc;
};
mẫu
void prompt(const std::string &question, T &answer)
{
std::cout << question;
std::cin >> answer;
}
int chính()
{
Answers info { };
prompt("Who: ", info.name);
if (!std::cin) { std::cerr << "Input failed!\n"; return -1; }
prompt("Age: ", info.answer);
if (!std::cin) { std::cerr << "Input failed!\n"; return -1; }
std::cout << "\nYou claim to be " << info.name << " with an age of " << info.answer << ".\n";
}
Đầu ra:
Who: Just
Age: 34
You claim to be Just with an age of 34.
Live Demo on coliru
似乎编辑后,OP 要求模板参数是返回类型:
#include
#include
struct Answers {
std::string name;
float answer;
int misc;
};
mẫu
T prompt(const std::string &question)
{
std::cout << question;
T answer;
std::cin >> answer;
return answer;
}
int main(int argc, char **argv)
{
Answers info {
prompt("Who: "),
prompt("Age: ")
};
if (!std::cin) { std::cerr << "Input failed!\n"; return -1; }
std::cout << "\nYou claim to be " << info.name << " with an age of " << info.answer << ".\n";
}
Đầu ra:
Who: Just
Age: 34
You claim to be Just with an age of 34.
Live Demo on coliru
比较第一种和第二种方法,您会注意到第二种方法的设计弱点:
虽然在第一种方法中,编译器可以推导出类型,但在第二种方法中这是不可能的。第二个模板实例的唯一区别 bản mẫu
函数 prompt()
将是返回类型——编译器不可推导。因此,第二个模板函数必须始终与显式模板参数一起使用(这会引入另一个出错的机会)。
一般建议:
当你试图写一个 bản mẫu
函数并且你不确定模板然后从一个简单的函数开始,然后是一个typedef
对于将成为模板参数的类型:
typedef std::string T;
void prompt(const std::string &question, T &answer)
{
std::cout << question;
std::cin >> answer;
}
编译,测试,欣赏,完成。
现在,它可以变成一个模板函数:
//typedef std::string T; // obsolete
mẫu
void prompt(const std::string &question, T &answer)
{
std::cout << question;
std::cin >> answer;
}
编译,测试,欣赏,完成。
Tôi là một lập trình viên xuất sắc, rất giỏi!