使用void函数设置main函数中变量的值

Oma*_*mar 1 c++

为什么num1价值等于0?我不明白.怎么会传递num1getScore功能,并使用cin不改变价值?如何更改基于什么是它的价值cinscore.

#include <iostream>
using namespace std;

void getScore(double);

int main(int argc, const char * argv[]) {
    double num1;
    getScore(num1);
    cout << "NUM 1 got set to " << num1 << endl;
    return 0;
}

void getScore(double score) {
    cout << "whats the score";
    cin >> score;
    cout << "num is " << score << endl;
}
Run Code Online (Sandbox Code Playgroud)

Kyl*_*e A 5

你通过num1了价值.这意味着这score是一个新的变量,其值已num1复制到其中.

你可能希望在这里发生的是num1通过引用传递.这是通过声明和定义函数来完成的:

void getScore(double&);

void getScore(double& score) {
    cout << "whats the score";
    cin >> score;
    cout << "num is " << score << endl;
}
Run Code Online (Sandbox Code Playgroud)

与号(&)表示您传递对变量的引用,而不是存储在变量中的值的副本.通过引用,score成为一种"昵称" num1.这意味着将值设置为score将真正设置该值num1.

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/