如何使一个类变量可用于多个.cpp文件? [英] How to make a variable avaliable to multiple .cpp files using a class?

查看:263
本文介绍了如何使一个类变量可用于多个.cpp文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题衍生自这一个< a>。

This question has derived from this one.

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

I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.

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

So, I made a simple example to understand how to make variables avaliable to the program parts. A modified version of the previous code would be:

#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() ,并让 entero 可用于所有人...

It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:

在上一个问题@NeilKirk中评论:不要使用全局变量。将必需的状态放入一个结构或类,并将其作为参数传递给函数(我还发现许多网页指向,不推荐使用全局变量)。

In the previous question @NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).

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

And, as far I can understand, in the answer provided by @PaulH., he is describing how to make variables avaliable by making them global. This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).

但是由于这种方法不推荐,所以我想感谢任何人,方法是将传递变量的代码作为函数参数或一些比工作全局变量更推荐的方法。

But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.

我研究了关于参数和类,但我是一个新手,我弄错了代码没有好的结果。

I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.

感谢任何帮助。

推荐答案

在头文件中定义类或结构体是一种方法,然后将头文件包含在所有源文件中需要类或结构。如果多个源文件以及变量声明(例如 extern int some_int_var; )和命名空间声明。

Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.

定义类时不会得到多个定义错误,编译器处理的概念,对于发生多个定义错误的链接器,类本身从不会传递。

You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.

以一个简单的例子,一个头文件和两个源文件。

Lets take a simple example, with one header file and two source files.

首先是头文件,例如 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

The above header file defines a namespace foo and in the namespace a class my_class and a function bar.

(对于像这样的简单程序,命名空间并不是必需的,但是对于更大的项目, sub>

(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)

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

Then the first source file, e.g. 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);
}

将所有三个文件放在同一个项目中,您现在应该得到一个可执行程序输出

Put all three files in the same project, and build. You should now get an executable program that outputs


In foo::bar(), value is 123
In main(), value is 456

这篇关于如何使一个类变量可用于多个.cpp文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆