简体   繁体   English

当C ++中的变量不在全局范围内并在自定义函数中使用时,如何设置它的值?

[英]How to set value of a variable in C++ when it's not in global scope and used in custom function?

The variables are not accepting the values I'm entering in my C++ program. 变量不接受我在C ++程序中输入的值。 I must avoid global variables and use only local variables. 我必须避免全局变量并仅使用局部变量。 And the function returns nothing, so I have used "void" instead of "int" type. 并且该函数没有返回任何内容,因此我使用了“void”而不是“int”类型。 Same thing happening when I use strings or any type of custom function. 当我使用字符串或任何类型的自定义函数时发生同样的事情。 Here is the example to explain my problem: 以下是解释我的问题的示例:

#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)

You can use pass by reference (or by pointer, for the educational purpose): 您可以使用按引用传递(或通过指针,用于教育目的):

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

Arguments can be passed by value or by reference to a function. 参数可以通过值或通过引用传递给函数。
When you pass an argument by a value (which is what you are doing), a separate copy is created of the variable and is stored in a different memory location. 当您通过值传递参数时(您正在执行此操作),将创建变量的单独副本,并将其存储在不同的内存位置。
When you pass by reference (using a pointer), same memory location is referenced. 当您通过引用传递(使用指针)时,将引用相同的内存位置。 Basically in your code you are creating a separate copy of the variable referenced by the same name and modifying that copy and expecting the changes in the original. 基本上在您的代码中,您正在创建由同一名称引用的变量的单独副本,并修改该副本并期望原始更改。 The solution is to use pointers. 解决方案是使用指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM