开发者

Class Definition Instance Instantiation Question

I have a class imgmanager that allows me to load all my images exactly once, it's quite nice, and while prototyping I had all of my files in one place, so I didn't have to worry about cyclical definitions. However after separating all of my classes I have a problem.

My Header File

#ifndef IMAGEMANAGER_H   
#define IMAGEMANAGER_H
#include "Img.h"
#include <vector>
#include <map>
#include <string>

class imgmanager{
 protected:
 std::vector<sf::Image*> images;
 std::map<std::string,int> positions;
 public:
开发者_开发知识库 sf::Image* addimg(std::string path); //relative to resources
 sf::Image* getimg(std::string path);
 int size();
 virtual ~imgmanager();
 sf::Image* operator[](int);
}imagemgr;

#endif

With the instance created after the } and before the ; my compiler complains at me:

So I ask: What should I do to have a global instance of my imagemgr class? Should I just make a global header file and create an instance? (in this particular case I can just make a global variable in my main.cpp, none of the headers require the instance)

Class Definition Instance Instantiation Question


Don't create object instances in headers.

Create your object instance in one source file.

If you need to access it across multiple Translation Units, put this in your header:

extern imgmanager imagemgr; // declaration

This will inform all code that can "see" the header that there exists a so-named object; but it will still only actually be defined in the one source file where you wrote:

imgmanager imagemgr; // definition

(This is analogous to the way in which you declare functions in a header, but define them in precisely one source file:

void f(); // declaration
void f() { ... } // definition

)


The above general advice dutifully imparted, I would now question the rationale of having a class at all if you're only going to use one, single, global instance of it. Either make it a "singleton" class, or use free functions in a namespace instead.


If you require a single global instance, i suggest you make the ImageManager a "Singleton". I'm unsure what to do for complex types, but for a global declaration of a simple data-type you should declare the variable "extern" in the header, and instantiate it in exactly one module (.cpp file).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜