跨多个类使用私有静态变量 [英] Using private static variable across multiple classes

查看:132
本文介绍了跨多个类使用私有静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类为我的一个程序,在窗口的不同位置绘制图像序列。该类有多个实例,但它是在窗口内的所有位置绘制的相同的图像序列。我想防止多个实例的类初始化多个图像序列,以避免吃记忆,我有图像序列变量作为静态变量

I've a class for my one of programs which is drawing image sequences at different positions on the window. The class has multiple instances but it's the same image sequence which is being drawn at all the positions inside the window. I want to prevent multiple instances of class initializaing multiple image sequences to avoid eating memory, for which I have the image sequence variable as static variable

class Drawer{
private:
static ImageSequence imgSequence;
};

在.cpp文件中,我将执行以下操作初始化静态变量。

In the .cpp file, I am doing the following to initialize the static var.

#include "Drawer.h"

ImageSequence Drawer::imgSequence = ImageSequence();



<在哪里放置这些方法,使每个Drawer类实例化不会预加载框架一次又一次。

However, I have two methods to specify the path to image sequences and preload al frames - and confused about where to put these methods so that each Drawer class instantiation does not preload the frames time and again. How'd this be done in C++?

- EDIT
要求的两种方法:i)loadSequence,ii)preloadAllFrames />

--EDIT The two methods as asked for: i) loadSequence, ii)preloadAllFrames();

    loadSequence(string prefix, string firstFrame, string lastFrame){
    for(int i=0;i<numFrames;++i){
    //adds and pushes values of all the files in the sequence to a vector
    }
}

preloadAllFrames(){
for(int i=0;i<numFrames;++i){
//create pointers to image textures and store then in a vector so that it doesn't take time to load them for drawing
}
}


推荐答案

有静态指针,而不是实例,并在静态方法中初始化:

Just have a static pointer instead of instance and initialize in a static method:

class Drawer{
private:
    static std::unique_ptr<ImageSequence> imgSequence;
public:
    static void initializeMethod1() 
    {
        if( imgSequence ) return; // or throw exception
        imgSequence.reset( new ImageSequence( ... ) );
        ...
    }

    static void initializeMethod2() {}
    {
        if( imgSequence ) return; // or throw exception
        imgSequence.reset( new ImageSequence( ... ) );
        ...
    }

    static ImageSequence &getSequence() 
    { 
        if( !imgSequence ) throw std::runtime_error( "image sequence is not intialized" );
        return *imgSequence;
    }
};

这篇关于跨多个类使用私有静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆