2015-06-21 50 views
-2

我想提出一個統計代碼控制檯應用程序中,C++的Visual Studio 2013年如何在C++中的void中設置一個全局int?

我已經全球int X設定據我所知,和我有一些void所做出起來,問題是我不知道該如何在void內部設置新的全球int,並重新使用int main內部的int(更新)。

請大家幫忙。

#include < iostream> 
using namespace std; 
int x = 0; 
void change(int x); 
void change2(int x); 
int main() 
{ 
change; 
system("PAUSE"); 
change2; 
return(0); 
} 
void change(int x) 
{ 
x = 5; 
cout << x << endl; 
} 
void change2(int x) 
{ 
x = (5 + 1); 
cout << x << endl; 
} 

我認爲那是一個簡化版本

+0

如果您想要查看代碼並找回我,我很樂意發佈它。 –

+1

請發佈您的代碼。 –

+0

Ofcourse我們希望看到的代碼。試想一下,你是我們中的一員,忘記了你對程序的一切瞭解。然後再讀你的問題。你知道它在說什麼嗎? – Slyps

回答

-2

作用域是該計劃的一個地區,從廣義上說有三個地方,其中的變量可以聲明:

內部函數或塊,被稱爲局部變量,

所有被稱爲全局變量的函數之外。

儘管您可以使用靜態全局塊來保存變量的最後修改值,但您不能在局部塊中聲明全局變量。

#include "example.h" 


int global_foo = 0; 
static int local_foo = 0; 


int foo_function() 
{ 
/* sees: global_foo and local_foo 
    cannot see: local_bar */ 
    return 0; 
} 

即使他的做法不是一個良好的編程習慣,而如果全局變量是多個.c文件中使用,你不應該對它做靜態聲明。相反,您應該在需要它的所有.c文件包含的頭文件中聲明它爲extern。

Refer this for further details.

+1

「我們將在後面的章節中瞭解什麼是函數和參數」?你正在發佈某人的編碼教程? – kfsone

+0

@kfsone你在說什麼? –

+1

您的答案似乎直接從http://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm –

0

你的參數int x隱藏全局變量int x,這就是爲什麼功能不會改變全球。

通過對每個聲明的變量使用不同的名稱,可以輕鬆避免此問題。

+0

你能提供一個我上面做的示例代碼的例子嗎? –

0

好吧,讓我們來看看你的代碼...

#include <iostream> 

using namespace std; 
int x = 0;    // a global variable. 

void change(int x);  // declares a function taking an int, returning void 
void change2(int x); // declares another function with same signature 

int main() 
{ 
    change;    // declare a reference to function change() 
         // no function call: statement has no effect 
    system("PAUSE"); 
    change2;    // declare a reference to function change2() 
         // no function call: statement has no effect 
    return(0); 
} 

void change(int x)  // defines a previously declared function 
{      // argument x is passed by copy 
    x = 5;    // sets local variable x to 5 
    cout << x << endl; // global variable x is not affected 
} 
void change2(int x)  // defines another previously declared function 
{      // argument x is passed by copy 
    x = (5 + 1);   // sets local variable x to 5+1 
    cout << x << endl; // global variable x is not affected 
} 

如果你想改變全局變量x,那麼你一定不能與局部變量隱藏(或明確地改變了全局變量):

int x;     // global variable 
void change_x_to(int i) 
{ 
    x=i;     // assigns local variable i to global variable x 
} 

void change2_x_to(int x) 
{ 
    ::x=x;    // assigns local variable x to global variable x 
} 

int main() 
{ 
    change_x_to(5); 
    change2_x_to(x+1); // the global x (of course) 
    assert(x==6); 
}      // return 0; is automatically created for main() 
相關問題