开发者

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 designs


Here's steps to make it work better:

  1. Add a struct containing all your objects near main().
  2. pass it to draw(MyStruct &s); via reference parameter.
  3. 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

};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜