开发者

Accessing variables outside the program in C++

id.cpp

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
public:
    static int a;
};
int A::a=20;

class b
{
public:
    b()
    {
     cout<<A::a<<endl;
    }
};

int main()
{
    b *b1 = new b();
    return 0;
}

id1.cpp

#include "stdafx.h"
#include <iostream>
using namespace std;

class c
{
public:
    int get()
    {
        cout<<A::a<<endl;
    }
};
int main()
{
    c c1;
    c1.get();
    return 0;
}

This is the way they have declared and got the output in one program but when I'm trying it I'm getting errors as the class is not a namespace 开发者_高级运维or the program id is not included in the id1 file... How to get the variable that is stored in one file into the other file without using namespace and including the header file is there any option for it?


Two separate programs as shown (they're separate because they both define main()) cannot share variables in any simple way.

If the two separate files were to be integrated into a single program, so one of the main() programs was replaced, then you would fall back on the standard techniques of declaring the variable A::a in a header and using that header in both modules. The header would also define class A. This is the only sane way to do it.

You could write the definition of the class twice, once in each file, and declare the variable as an extern in one file and define it in the other, but that is not particularly sensible even in this simple case and rapidly degenerates into unmaintainable disaster if the code gets any more complex and there are more shared variables.

Of course, you might want to consider not using a global variable at all, but provide instead an accessor function. However, you still end up with a header declaring the services provided by the class A and the code implementing those services, and the code consuming those services.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜