C ++:声明一个全局类并从其他类访问它? [英] C++: Declare a global class and access it from other classes?

查看:64
本文介绍了C ++:声明一个全局类并从其他类访问它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该从main()全局声明并从程序中其他声明的类访问的类,该怎么做?

I have a class which should be declared globally from main() and accessed from other declared classes in the program, how do I do that?

class A{ 
    int i; 
    int value(){ return i;}
};

class B{ 
   global A a; //or extern?? 
   int calc(){
       return a.value()+10;
   }
}

main(){
   global A a;
   B b;
   cout<<b.calc();
}

推荐答案

您可能真的不想这样做,但是,如果必须-在包含main的文件中:

You probably really do not want to do this, but if you must - in the file that contains main:

#include "A.h"
A a;

int main() {
 ...
}

,然后在需要访问全局文件的文件中:

and then in the files that need to access the global:

#include "A.h" 
extern A a;

您需要将A的声明放入A.h头文件中,以使其正常工作.

You will need to put the declaration of A in the A.h header file in order for this to work.

这篇关于C ++:声明一个全局类并从其他类访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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