【发布时间】:2022-11-21 10:49:11
【问题描述】:
我有一个简单的问题。在我的计算机课上,我被告知当您想修改原始输入并将其存储在参考内存中以供将来访问时,将使用参考参数。您将 & 附加到变量的末尾以执行此操作,例如对于函数:void firstName(string name)
然而,我正在审查我的实验室导师的一个程序,你在其中输入你的名字和姓氏,例如 John Smith,它输出为 Smith, John。
在这种情况下,当您输入 John Smith 时,似乎以下 void 函数不应使用引用参数,而应使用常规参数 void readName(string name)
除非它没有,否则它使用一个参考参数:它被设置为 void readName(string& name)
为什么在这种情况下使用参考参数?在我看来,它只是提取名称然后对其进行计算?我看不到字符串的修改在哪里发生以证明它是一个参考参数。
任何帮助将非常感激。
非常感谢..
//
// This program reads the first name and last name of a student,
// and prints it as last name, first name
//
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Function prototypes
void readName(string&);
void extract(string, string&, string&);
void printName(string, string);
// Constant declarations
int main()
{
string name, firstName, lastName;
char response;
do {
readName(name);
extract(name, firstName, lastName);
printName(firstName, lastName);
cout << "Try again (Y/N)? ";
cin >> response;
cin.ignore(100, '\n');
} while (tolower(response) == 'y');
return 0;
}
// Function definitions
// Purpose: gets the student's name from a user
// Parameters: Inputs --
// Outputs -- name -- string
// Inputs/Outputs --
// Returns:
void readName(string& name){
cout << "Enter student's first name and last name -- ";
getline(cin, name);
}
// Purpose: extracts firstName and lastName
// Parameters: Inputs -- name is string
// Outputs -- firstName and lastName are string
// Inputs/Outputs --
// Returns:
void extract(string name, string& firstName, string& lastName){
firstName = "";
lastName = "";
string::size_type i;
for (i = 0; !isspace(name.at(i)); i++)
firstName = firstName + name.at(i);
for (i = i + 1; i < name.length(); i++)
lastName = lastName + name[i];
}
// Purpose: prints firstName and lastName in the form of lastName, firstName
// Parameters: Inputs -- firstName and lastName are string
// Outputs --
// Inputs/Outputs --
// Returns:
void printName(string firstName, string lastName){
cout << lastName << ", " << firstName << endl;
}
期望 void readName(string name) 在此程序中工作,但事实并非如此。 void readName(string& name) 是唯一适用于执行所需功能的语法。
【问题讨论】:
-
“在我看来,它只是提取名称然后对其进行计算?“你怎么看?
readName只是读取名称。这需要将名称写在后续代码可以看到的地方。”我看不到字符串的修改在哪里发生以证明它是一个参考参数。“这是readName的部分读名字. -
除了参考参数(您的讲师可能将它们用于教学目的),我更喜欢没有任何参数的
std::string readName()。
标签: c++