Structure of program
I have few files:
main.cpp:
int main{
...
while(1){
...
draw();
...
}
...
return 0;
}
and draw.cpp: 开发者_如何学JAVAI want to see objects and all manipulations here. I cant make objects local to draw(), because draw() is inside loop, so I will get many object constructor/destructor calls - so they are global. Also I ve made init block to prevent unnecessary calls/assignments
draw.cpp:
Object A, B;
int initialized = 0;
void draw(){
if(!initialized){
A.initialization;
B.initialization;
initialized = 1;
}
A.move(1,1);
B.rotate(45);
}
It works, but Im looking for better way to organize my code
Added: Thanks for answers, looks like I have to read something about pattern designsHere's steps to make it work better:
- Add a struct containing all your objects near main().
- pass it to draw(MyStruct &s); via reference parameter.
- you're done.
Option 1
Define a new Class called Draw and put the attributes into it. You need to modify main and draw files for this. With this you can avoid declaring anything global
Option 2
Define a class within draw.cpp called draw and add your current global variables as static member variables. Initialize and use them using static functions. With this you dont have to change main. This design technique is called Singleton (one of the design patterns)
Example code draw.cpp
class Draw
{
public:
object A, B;
static void init()
{
// init A
// init B
isInitialized = 1;
}
static int isInitialized;
static Object & getA()
{
if(isInitialized == 0)
{
init();
}
return A;
}
// similarly B
};
精彩评论