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

How to make a variable available to multiple .cpp files using a class?

本文关键字:一个 用于 cpp 文件 何使用 变量      更新时间:2023-10-16

这个问题是从这个问题衍生出来的。

我有一个工作程序,必须分成多个部分。在这个程序中,需要在程序的某些部分多次使用一个变量(现在它是一个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评论:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter(我也发现许多网页指出不建议使用全局变量)。

并且,据我所知,在@PaulH提供的答案中。,他正在描述如何通过使变量成为全局变量来使其可用。这个答案非常有用,它不仅可以很好地处理char数组,还可以处理int s, string s和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

方法是在头文件中定义一个类或结构体,然后在所有需要这些类或结构体的源文件中包含这个头文件。如果多个源文件需要,也可以将函数原型或预处理器宏放在头文件中,以及变量声明(例如extern int some_int_var;)和namespace声明。

你不会从定义类中得到多个定义错误,因为类是一个由编译器处理的概念,类本身永远不会传递给发生多个定义错误的链接器。


让我们举一个简单的例子,一个头文件和两个源文件。

头文件,例如myheader.h:

#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
    // Define a class
    class my_class
    {
    public:
        my_class(int val)
            : value_(val)
        {}
        int get_value() const
        {
            return value_;
        }
        void set_value(const int val)
        {
            value_ = val;
        }
    private:
        int value_;
    };
    // Declare a function prototype
    void bar(my_class& v);
}
#endif // MYHEADER_H

上面的头文件定义了一个命名空间foo,在命名空间中定义了一个类my_class和一个函数bar

(对于这样一个简单的程序来说,名称空间是严格不需要的,但是对于更大的项目来说,它就变得更需要了。)

然后第一个源文件,例如main.cpp:

#include <iostream>
#include "myheader.h"  // Include our own header file
int main()
{
    using namespace foo;
    my_class my_object(123);  // Create an instance of the class
    bar(my_object);  // Call the function
    std::cout << "In main(), value is " << my_object.get_value() << 'n';
    // All done
}

最后第二个源文件,例如bar.cpp:

#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
    std::cout << "In foo::bar(), value is " << val.get_value() << 'n';
    val.set_value(456);
}

将这三个文件放在同一个项目中,然后构建。现在您应该得到一个输出

的可执行程序<>之前在foo::bar()中,值是123在main()中,value是456

我更愿意为全局数据提供一个功能接口。

. h文件:

extern int get_entero();
extern void set_entero(int v);

. cpp文件:

static int entero = 10;
int get_entero()
{
   return entero;
}
void set_entero(int v)
{
   entero = v;
}

然后,在其他地方使用这些函数。

#include "the_h_file"
void function()
{
    cout << get_entero() << endl;
    //action1...;
}
void separated_function()
{
    cout << get_entero() << endl;
    //action2...;
}
int main( int argc, char *argv[] )
{
    function();
    separated_function();
    cout<< get_entero() <<endl;
    //something else with the mentioned variables...;
    return 0;
}

如果您不打算修改变量,通常可以将其设置为全局。但是,最好使用const关键字声明它,向编译器发出不应该修改它的信号,如下所示:

const int ENTERO = 10;

如果你使用多个cpp文件,也可以考虑使用头文件来声明你的结构和函数。

如果您打算修改变量,只需在函数参数中传递它。

相关文章: