C++,Typedef 静态 getInstance 函数

C++, Typedef a Static getInstance function

我有这个单例 "TextureHandler" Class 使用这个 "TextureHandler::getInstance()->functionName()" 效果很好,但是...我想做的是为 getInstance() 函数制作一个 typedef "TxHandler",所以我可以像这样使用它 "TxHandler->functionName()",但我收到此错误:expected initializer before 'TxHandler'.

#ifndef TEXTUREHANDLER_H
#define TEXTUREHANDLER_H

#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <iostream>
#include <string>
#include <map>
#include "Defs.h"

// Engine's texture handler class
class TextureHandler
{
    // private constructor for singleton
    TextureHandler() {}
    static TextureHandler* instance;

    // textures string map
    map<string, SDL_Texture*> tMap;

    public:
        // getInstance singleton function
        static inline TextureHandler* getInstance()
        {
            if(instance == NULL)
            {
                // create a pointer to the object
                instance = new TextureHandler();
                return instance;
            }
            return instance;
        }

        bool load(SDL_Renderer* renderer, string id, const char* filename);
        bool loadText(SDL_Renderer* renderer, string id, const char* text, TTF_Font* font, SDL_Color color);
        void render(SDL_Renderer* renderer, string id, int x, int y, int w=0, int h=0, int center=0, SDL_Rect* clip=NULL, SDL_RendererFlip flip=SDL_FLIP_NONE);
        void free(string id);
        int getWidth(string id);
        int getHeight(string id);
};

// TextureHandler instance typedef
typedef TextureHandler::getInstance() TxHandler;

#endif

typedef 允许您为 类型 创建别名。您不能使用它来命名该类型的实例。

最接近您所追求的功能的方法是将 TextureHandler::getInstance() 的结果存储在一个指针中:

TextureHandler* TxHandler = TextureHandler::getInstance();
....
TxHandler->functionName();

正如 juanchopanza 在评论中所说,typedef 声明了一个类型的别名。不是一般的宏。

如果不想重复输入TextureHandler::getInstance(),可以使用宏:

#define TxHandler TextureHandler::getInstance()

但这只是语法糖,编译器会生成完全相同的代码。