![](/img/trans.png)
[英]Global variable priority over local variable when global function called in scope of local variable c++
[英]How to set value of a variable in C++ when it's not in global scope and used in custom function?
變量不接受我在C ++程序中輸入的值。 我必須避免全局變量並僅使用局部變量。 並且該函數沒有返回任何內容,因此我使用了“void”而不是“int”類型。 當我使用字符串或任何類型的自定義函數時發生同樣的事情。 以下是解釋我的問題的示例:
#include <iostream>
void sum (int a, int b, int c);
int main (void)
{
int a = 0, b = 0, c = 0;
sum (a, b, c);
std::cout << a << b << c;
return 0;
}
void sum (int a, int b, int c) // It doesn't have to be the same variable name :)
{
std::cout << "Enter value of a:\n";
std::cin >> a;
std::cout << "Enter value of b:\n";
std::cin >> b;
std::cout << "Enter value of c:\n";
std::cin >> c;
a = b+c;
}
通過引用傳遞 :
void sum (int &a, int &b, int &c)
您可以使用按引用傳遞(或通過指針,用於教育目的):
void sum (int& a, int& b, int& c);
void sum (int* a, int* b, int* c);
int main (void)
{
int a = 0, b = 0, c = 0;
sum (a, b, c);
std::cout << a << b << c;
a = 0, b = 0, c = 0;
sum (&a, &b, &c);
std::cout << a << b << c;
return 0;
}
void sum (int& a, int& b, int& c)
{
std::cout << "Enter value of a:\n";
std::cin >> a;
std::cout << "Enter value of b:\n";
std::cin >> b;
std::cout << "Enter value of c:\n";
std::cin >> c;
a = b+c;
}
void sum (int* a, int* b, int* c)
{
std::cout << "Enter value of a:\n";
std::cin >> *a;
std::cout << "Enter value of b:\n";
std::cin >> *b;
std::cout << "Enter value of c:\n";
std::cin >> *c;
*a = *b + *c;
}
參數可以通過值或通過引用傳遞給函數。
當您通過值傳遞參數時(您正在執行此操作),將創建變量的單獨副本,並將其存儲在不同的內存位置。
當您通過引用傳遞(使用指針)時,將引用相同的內存位置。 基本上在您的代碼中,您正在創建由同一名稱引用的變量的單獨副本,並修改該副本並期望原始更改。 解決方案是使用指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.