我很担心我会在这里添加什么样的变量: names 。我在C ++书中做了一个练习题,因为我正在学习C ++,现在正在使用References和指针,但是找不到解决方案。
仅供参考,问题是:
编写一个功能,提示用户输入他或她的名字和姓氏,作为两个单独的值 此函数应通过传递给函数的其他指针(或引用)参数将两个值都返回给调用者 首先尝试使用指针,然后使用引用。
#include <iostream>
#include <string>
#include <istream>
using namespace std;
struct someStruct{
string firstname;
string lastname;
};
void names(someStruct &firstname, someStruct &lastname) {
cout << "First Name: " << "\n";
cin >> firstname.firstname;
cout << "Last Name: " << "\n";
cin >> lastname.lastname;
// I was just curious is adding firstname to firstname would work... and it did
cout << lastname.lastname << ", " << firstname.firstname;
cin.get();
}
int main() {
names();
// I don't know what to put here, above, as parameters
cin.get();
}
答案 0 :(得分:1)
你的代码毫无意义,你为什么两次通过someStruct
?
对于参考部分,您应该具有以下内容:
void names(someStruct &s) { // <<<< Pass struct once as a reference
cout << "First Name: " << "\n";
cin >> s.firstname;
cout << "Last Name: " << "\n";
cin >> s.lastname;
}
和main()
:
int main() {
someStruct x; // <<<< Create an instance of someStruct
names(x); // <<<< Pass it as parameter
cout << "Input was: firstName = " << x.firstname
<< ", lastName = " << x.lastname
<< endl;
cin.get();
}
对于指针部分,你应该有:
void names(someStruct *s) { // <<<< Pass struct once as a reference
cout << "First Name: " << "\n";
cin >> s->firstname;
// ^^ Note the difference in dereferencing
cout << "Last Name: " << "\n";
cin >> s->lastname;
// ^^ Note the difference in dereferencing
}
和main()
:
int main() {
someStruct x; // <<<< Create an instance of someStruct
names(&x); // <<<< Pass the address of x as parameter
// ^ Note the addess-of operator here
cout << "Input was: firstName = " << x.firstname
<< ", lastName = " << x.lastname
<< endl;
cin.get();
}