【发布时间】:2015-02-28 04:58:06
【问题描述】:
我试图确保我了解使用 & 符号来引用变量是什么。我知道有人问过其他类似的问题,但我想看看我给出的代码示例是否正确使用它。
示例代码:
// function prototype
GetBalance(float &balance);
int main()
{
float balance;
bool choice = true;
if (choice == true)
GetBalance(float &balance);
else
cout << "error" << endl;
return 0;
}
GetBalance(float &balance)
{
cout << "please enter the balance: " << endl;
cin >> balance;
}
所以在主函数中声明了浮点变量。
函数 GetBalance 引用在主函数中声明的变量。这样当用户输入余额时,输入就被分配给余额变量。
这对吗?
如果不是,我想做的事情可能吗?
我想将在 GetBalance 函数中输入的金额分配/传递给 main() 中声明的变量“balance”。
【问题讨论】:
标签: c++ c++11 pass-by-reference