C++ 跨函数使用变量

C++ 跨函数使用变量,c++,function,C++,Function,假设我在一个函数中声明一个变量,如下所示: 虚空一号{ INTC; } 我怎样才能在不同的功能中做到这一点 void j() { cout << c << endl; } 变量c在调用j的上下文中不存在,因此必须将其作为全局变量或返回值传递 int i(){ int c = 2; return c; } int i将返回c,它可以传递给其他构造函数 void j(const int c){ std::cout << c &l

假设我在一个函数中声明一个变量,如下所示:

虚空一号{ INTC; }

我怎样才能在不同的功能中做到这一点

void j() {
    cout << c << endl;
}
变量c在调用j的上下文中不存在,因此必须将其作为全局变量或返回值传递

int i(){
    int c = 2;
    return c;
}
int i将返回c,它可以传递给其他构造函数

void j(const int c){
    std::cout << c << std::endl;
}

让我们从基础开始:

在C++中,变量的缺省存储类是Auto.</P> 这意味着在块内声明的变量只有在声明后才能在该块内使用

块用大括号、循环、if语句、函数等标记

void i() {

     //c is not declared here and is unavailable
     int c;
     //c is available 

        for(int i=0; i<2; i++)
        {
         //c is also available here, because it is declared in larger scope
        }
}
//c is not recognized here because it is declared only inside the scope of i()

 void j()
 {
  int c; //this is variable c. it has nothing to do with the c that is declared in i()

        for(int i=0; i<2; i++)
        {
         int d; //this variable gets created and destroyed every iteration
        }

  //d is not available here.
 }
默认情况下,在函数体中声明的变量将仅在声明点之后的函数范围内存在

在您的问题中,您没有描述您希望这两个功能如何通信,因此很难找到合适的方法


如果要在函数之间传递相同的值,则应读入参数传递值和函数返回值。还有一种方法是全局变量,除非绝对需要,否则不推荐使用,但绝对需要学习

最好的方法取决于您对c的实际操作。也就是说,如果c对i的调用不是唯一的,那么您可以使用全局变量在任何地方访问它:

int c;
void i(){
  c = c++; //uses c, pun intended
}
void j(){
  cout << c << endl;
  c++; //can change c
}
请注意,上述i中的c和j中的c不是同一个变量。如果你在j中改变c,它在i中就不会改变,就像全局方法一样

如果希望变量对i是唯一的,但对j是可访问的,则可以通过如下所示的指针not或refence传递变量:

void i(){
  int c=0;
  j(c);
}
void j(int &c){
  cout << c << endl;
  c++; //can change c in i()
}

注意:这里的术语相当随意,我甚至没有使用你可能想了解更多的单词

你把j叫做i吗?@NathanOliver那不是爪哇吗?runs@soulsabr抱歉,我不明白。@NathanOliver他说了一个双关语,好像你指的是JNIJava本机接口。别打我,我只是个麻烦。。。这是他糟糕的双关语@谢谢。现在我知道他/她的例子使用简单的函数;不是构造器。他/她必须担心的最糟糕的情况是向前声明函数而不是创建类/结构。只有一种可能的方法,顺便问一下,为什么要将c作为常量传递?好习惯是出于太多的原因而进入IMHO,而这些原因太多了,无法进入旁注。有一些很好的论据支持和反对使用const。
void i() {

     //c is not declared here and is unavailable
     int c;
     //c is available 

        for(int i=0; i<2; i++)
        {
         //c is also available here, because it is declared in larger scope
        }
}
//c is not recognized here because it is declared only inside the scope of i()

 void j()
 {
  int c; //this is variable c. it has nothing to do with the c that is declared in i()

        for(int i=0; i<2; i++)
        {
         int d; //this variable gets created and destroyed every iteration
        }

  //d is not available here.
 }
int c;
void i(){
  c = c++; //uses c, pun intended
}
void j(){
  cout << c << endl;
  c++; //can change c
}
void i(){
  int c;
  j(c);
}
void j(int c){
  cout << c << endl;
  c++; //cannot change c in i()
}
void i(){
  int c=0;
  j(c);
}
void j(int &c){
  cout << c << endl;
  c++; //can change c in i()
}