2017-10-05 83 views
0

所以,我有一个主要方法调用方法多次(C++)

int main() { 
int x = 0; 
inc(x); 
inc(x); 
inc(x); 
std::cout << x << std::endl; 
} 

我试图让我的输出是“3”,但无法弄清楚,为什么每次INC(X)被称为X重置为0

我INC方法:

int inc(int x){ 
    ++x; 
    std::cout << "x = " << x << std::endl; 
    return x; 
} 

我的输出:

x = 1 
 
    x = 1 
 
    x = 1 
 
    0

为什么X复位后,每次调用INC(x)和我如何可以解决此不编辑我的主要功能

回答

1

而不是

inc(x); 

我想你需要

x = inc(x); 

你现在可以拍你的头。

+0

这就要求他改变的main() - 他的问题,规定他不能这样做。 – Brian

0

你传递的“X”来公司()的值,因此公司制造的改变()不会在主可见()。

0

如果你想要使用X被改变,你需要通过参考,而不是把它作为一个值。此外inc()将需要返回无效,这是有道理的。这里是一个例子。

// adding & before x passes the reference to x 
void inc(int &x){ 
    ++x; 
    std::cout << "x = " << x << std::endl; 
} 
int main() { 
    int x = 0; 
    inc(x); 
    inc(x); 
    inc(x); 
    std::cout << x << std::endl; 
} 

此打印

x = 1 
x = 2 
x = 3 
3