【问题标题】:Parameters to use in a referenced function c++在引用函数 c++ 中使用的参数
【发布时间】:2015-06-23 05:57:18
【问题描述】:

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

只是为了背景信息,问题问:

编写一个函数,提示用户输入他或她的名字和姓氏,作为两个单独的值。
此函数应通过传递给函数的附加指针(或引用)参数将这两个值返回给调用者。
尝试先使用指针,然后使用引用。

#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();
}

【问题讨论】:

  • names()带指针你知道怎么做吗?

标签: c++ pointers reference


【解决方案1】:

你的代码没有意义,你为什么要传递someStruct 两次?

对于 reference 部分,您应该有类似的内容:

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();
}

对于 pointer 部分,你应该有类似的东西:

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();
}

【讨论】:

  • 哦,我没有这么想。谢谢。
  • 另外,我认为每当您在函数中设置涉及引用的参数时,它们都必须指向一个初始化值。或者,设置参数是否初始化值?当它引用未在其他任何地方初始化的值时,我对该函数的工作方式感到困惑。解释会有所帮助。
  • @MaxKhan 值由编译器生成的默认构造函数 someStruct 使用包含的成员变量的默认构造函数初始化(std::string::string() 用于您的情况 => 空 string),除非您定义自己创建一个默认构造函数,并使用 member initializer list 初始化它们。
  • 好的,我现在明白了。谢谢,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2015-08-01
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多