gpt4 book ai didi

c++ - 如何使用一个类使一个变量可用于多个 .cpp 文件?

转载 作者:行者123 更新时间:2023-11-30 01:46:42 24 4
gpt4 key购买 nike

这个问题来自this one .

我有一个工作程序,它必须分成多个部分。在这个程序中,需要在程序的某些部分多次使用一个变量(现在它是一个 GTK+ :P),这些变量最终将在单独的 .cpp 文件中。

所以,我做了一个简单的例子来理解如何让变量对程序部分可用。先前代码的修改版本为:

#include <iostream>

using namespace std;

int entero = 10;

void function()
{
cout<<entero<<endl;
//action1...;
}

void separated_function()
{
cout<<entero<<endl;
//action2...;
}

int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}

需要正确拆分代码,将function()another_function()main()分开.cpp文件,并使 entero 对所有文件可用...但是:

在上一个问题中@NeilKirk 评论道:不要使用全局变量。将需要的状态放入一个结构体或类中,并根据需要将其作为参数传递给函数(而且我也发现很多网页都指出不建议使用全局变量)。

而且,据我所知,在@PaulH. 提供的答案中,他描述了如何通过使变量成为全局变量来使其可用。这个答案非常有用,它不仅适用于 char 数组,而且适用于 intstring 和 GTK+ 变量(或指向变量的指针 :P)。

但由于不推荐使用这种方法,我会感谢任何能够展示将变量作为函数参数传递的代码的正确方法或比 - 工作 - 全局变量方法更推荐的其他方法的任何人。

我研究了参数和类,但是我是新手,我把代码搞砸了,没有什么好结果。

最佳答案

如果你想要和全局变量一样的功能,你需要给参数作为引用

#include <iostream>

using namespace std;


// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}

void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}

int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable

// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);

cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}

输出:

10
11
12

关于c++ - 如何使用一个类使一个变量可用于多个 .cpp 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32730915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com