gpt4 book ai didi

c++ - 在引用函数中使用的参数 c++

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

我很困惑我要在我的函数中放入什么样的变量:names。我正在做一本 C++ 书中的练习题,因为我正在学习 C++,现在正在引用和指针上,找不到解决方案。

仅作为背景信息,问题要求:

Write a function that prompts the user to enter his or her first name and last name, as two separate values.
This function should return both values to the caller via additional pointer(or reference) parameters that are passed to the function.
Try doing this first with pointers and then with 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();
}

最佳答案

你的代码没有意义,为什么要传递两次 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();
}

关于c++ - 在引用函数中使用的参数 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30990257/

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