有多少个全球人? [英] How many globals?

查看:88
本文介绍了有多少个全球人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


首先让我解释一下代码,然后再问一个问题.

主要外观如下:

Hi,
Let me first explain the code and then I will ask a question.

The main looks as follows:

#include <iostream>
#include "A.h"
#include "B.h"

int _tmain(int argc, _TCHAR* argv[])
{
   B b;

   std::cout << &constA << std::endl;
   b.Print();

   return 0;
}
//-----------------------------

and A.h:

class A
{
public:
   A( int v): val(v) {}
 
private:
   int val;
};

const A constA(10);

//----------------------------

and B.h + B.cpp

file B.h :

class B
{
public:
  void Print();

};

file B.cpp:

#include "B.h"
#include "A.h"
#include <iostream>

void B::Print()
{
   std::cout << &constA << std::endl;
}

//----------------------------



好的.在头文件A.h中,声明了全局只读对象 constA .在应用中只能是这样的一个对象.
但是,当我在主要地址两次打印其地址时(一次在cout行中显式打印,然后调用B类的Print方法),我得到了两个不同的地址.为什么会发生?



OK. In header file A.h is declared global read-only object constA. It shall be only one such object in application.
But when I prints its address in main two times (one explicitly in cout line and then calling Print method of B class) I got two different addresses. Why does it occur? How to achieve one address of this const in the whole code?

推荐答案

您已经在头文件中定义了变量,然后将该文件包含在两个单独的编译单元中.这意味着已编译的文件B.obj和main.obj都将包含称为constA的变量.

要使其成为全局常量,需要在头文件中声明它,但仅定义一次:

在A.h中:
You have defined the variable in the header file, then included the file into two separate compilation units. This means that the compiled files B.obj and main.obj will both contain variables called constA.

To make it a global constant, it needs to be declared in the header file, but defined once only:

In A.h:
extern const A constA;



在A.cpp中:



In A.cpp:

#include "A.h"

const A constA(10);


您是否有理由这样做?我只是在此处阅读了.<
Is there a reason you need to do this? I just read here[^] that a compiler is free to store a const anywhere, thus it could actually be stored in multiple places. My guess is that a copy of constA is being stored on the local call stack in each instance.

BTW- It seems like what you really want is a Singleton object. There are many articles on how to make one of those.


这篇关于有多少个全球人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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