I am working on MFC SDI application, in which I include one C++ generic class, but I have a problem and am stuck on it.
I have a generic C++ class in Tree.h
and its implementation Tree.cpp
, as well as two more classes, say a_Class.h
and b_Class.h
.
The problem is:
I am making an instance of Tree.h
in a_Class.cpp
like this:
Tree *obj = new Tree()
I declared it it globally. Now, I want to use this very same object in b_Class
.
For this I use the extern
keywork, in b_Class.cpp
as follows:
extern Tree *obj;
This run fine, but it doesn't use the same object. In the background, it declares separate objects.
How can I fix this?
From your description it sounds like it should work. You might rewrite it differently, in a_Class.cpp add global function:
static Tree* obj = new Tree();
Tree* GetTreeObj() {
return obj;
}
in b_Class.h add:
extern Tree* GetTreeObj();
then use GetTreeObj() to retrieve Tree pointer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.