在C++中,单例模式是一种设计模式,它确保一个类只有一个实例,并提供一个全局访问点来获取这个实例。当你在子类中继承一个单例类时,可能会遇到没有调用子类函数的问题。这通常是由于以下几个原因造成的:
为了确保在继承单例时能够调用子类的函数,可以采取以下措施:
#include <iostream>
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
virtual void doSomething() {
std::cout << "Singleton::doSomething()" << std::endl;
}
protected:
Singleton() {}
virtual ~Singleton() {}
private:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
class DerivedSingleton : public Singleton {
public:
void doSomething() override {
std::cout << "DerivedSingleton::doSomething()" << std::endl;
}
};
int main() {
Singleton& singleton = DerivedSingleton::getInstance();
singleton.doSomething(); // 输出: DerivedSingleton::doSomething()
return 0;
}
通过上述方法,可以确保在继承单例时能够正确调用子类的函数,并且避免常见的陷阱和问题。
领取专属 10元无门槛券
手把手带您无忧上云