【问题标题】:Change a variable in main from a function [closed]从函数更改main中的变量[关闭]
【发布时间】:2014-08-25 22:54:31
【问题描述】:

我正在寻找类似于 python global 关键字的功能。我想从函数中更改 main 中声明的变量。

例如:

void f() {
    x = 5;
}

int main() {
    int x = 0;
    f();
    cout << x; // prints 5

}

有什么办法吗?

【问题讨论】:

标签: c++ scope global-variables


【解决方案1】:

使用传递给函数的引用

void f(int& x) {
    x = 5;
}

int main() {
    int x = 0;
    f(x);
    cout << x; // prints 5
}

或全局变量(不鼓励!)

int x = 0;

void f() {
    x = 5;
}

int main() {
    x = 0;
    f();
    cout << x; // prints 5
}

【讨论】:

  • 如果我通过引用传递数组,我将如何格式化?
  • @CSGregorian 你是什么意思“如果我通过引用传递一个数组,我将如何格式化?”?如何将std::array&lt;int,N&gt;std::vector&lt;int&gt; 打印到std::cout?!?这是一个完全不同的问题,正如你在这里所要求的!
  • 不,不,对不起,忘记 cout,这只是一个例子。如果我想传递一个数组,那就是void f(int (&amp;x)[]),对吧?
  • @CSGregorian 你不能很好地使用c样式数组类型的引用,坚持std::array&lt;int,N&gt;std::vector&lt;int&gt;来处理引用参数。你也应该澄清你关于这一点的问题。事实上,它与您在此处的评论中实际询问的内容无关!
猜你喜欢
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多