在Qt中实现单例模式可以使用静态成员变量和静态成员函数的方式。以下是一个示例:

class AimChoosedCent
{
public:
    static AimChoosedCent* GetInstance()
    {
        if (aimChoosed == nullptr)
        {
            aimChoosed = new AimChoosedCent();
        }
        return aimChoosed;
    }

private:
    AimChoosedCent() {} // 私有构造函数,防止外部创建对象
    static AimChoosedCent* aimChoosed; // 静态成员变量,用于保存单例对象的指针
};

AimChoosedCent* AimChoosedCent::aimChoosed = nullptr; // 静态成员变量初始化

// 使用示例
AimChoosedCent* aim = AimChoosedCent::GetInstance();

在以上示例中,AimChoosedCent类的构造函数被声明为私有的,这意味着外部无法直接创建该类的对象。通过GetInstance静态成员函数来获取单例对象的指针。在GetInstance函数内部,判断aimChoosed是否为空,如果为空则创建一个新的AimChoosedCent对象,并将其赋值给aimChoosed,最后返回aimChoosed的值。由于静态成员变量和静态成员函数属于类本身而不是对象,所以可以通过类名来访问它们

static public AimChoosedCent GetInstance if aimChoosed == null aimChoosed = new AimChoosedCent; return aimChoosed; 中文回答在qt中怎

原文地址: https://www.cveoy.top/t/topic/h637 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录