I have these files (simplified version)
a.h
class A
{
public:
A(int){}
int operator [](int a){return a;}
};
A a(2);
main.cpp
#include<a.h>
class B
{
public:
B(int){}
};
B b(a[2]);
int main()
{
//use b here...
}
Q: Can I use the above code ? Is it correct ?!
The code above (almost) compiles, but it probably doesn't do what you'd expect. A couple issues . . .
#include<a.h>
should probably be #include "a.h"
if a.h is located in the same directory as main.cpp.
B b(a[2])
might create a new instance of class A, instead of using the one you defined in a.h. Add extern A a;
before you use a
to tell your compiler that you want to use the a
declared in another file.
Finally, depending on your application sometimes global variables can be frowned upon. If it's appropriate, consider using encapsulation instead of global variables. Something like
Class B {
public:
B(int i){}
private:
A a(); // Or extern A a;
};
Would work if you only needed to access a from b.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments