gpt4 book ai didi

模板化单例的 C++ 工厂

转载 作者:行者123 更新时间:2023-11-28 00:14:34 29 4
gpt4 key购买 nike

这是一个简单的 C++ 项目,有 2 种设计模式:单例和工厂,sigleton 也是一个模板化类,一个接口(interface) (IHash) 和一个类 (Hash1)。一个简单的工厂类 (HashFactory) 创建一个 sigleton (Hash1); Hash1 继承接口(interface) IHash,理想情况下我有 Hash1、Hash2 .. HashN。

编译时出现错误,请问是什么问题?

g++  main.cpp 
main.cpp: In static member function ‘static IHash* HashFactory::get(int)’:
main.cpp:11:15: error: ‘static T& Singleton<T>::getInstance() [with T = Hash1]’ is inaccessible
static T &getInstance() {
^
main.cpp:76:50: error: within this context
if (type == 1)return &Hash1::getInstance();
^

剪切并粘贴此代码以对其进行编译:

#include <iostream>
using namespace std;
///////////////////////////////////////////////
//Class Singleton
template<class T>
class Singleton {
public:

static T &getInstance() {
if (!_instanceSingleton) {
_instanceSingleton = new T();
}
return *_instanceSingleton;
}

private:
static T *_instanceSingleton;
};

template<class T> T *Singleton<T>::_instanceSingleton = 0;

/////////////////////////////////////////////////
//Interface IHash
class IHash {

public:

void function1() {
cout << "function1";
}

virtual void recordHash(bool b) = 0;

~IHash() {
dispose();
}


private:

void dispose() {
cout << "dispose\n";
}
};

///////////////////////////////////////////////////
//Class Hash1 is a singleton and inherits IHash

class Hash1 : public IHash, Singleton<Hash1> {
friend class Singleton<Hash1>;
public:
void recordHash(bool b);
private:
//private constructor, is a sigleton
Hash1();
};

Hash1::Hash1() {
cout << "create Hash1\n";
}

void Hash1::recordHash(bool b) {
cout << b << " recordHash\n";
}


////////////////////////////////////////////////////
//Factory for IHash
class HashFactory {
public:
static IHash *get(int type) {
if (type == 1)return &Hash1::getInstance();
// if (type == 2)return &Hash2::getInstance();
// if (type == 3)return &Hash3::getInstance();
return 0;
}
};

//////////////////////////////////////////////////////

int main() {
int type=1;
IHash *a = HashFactory::get(type);
a->recordHash(true);
a->function1();
return 0;
}

最佳答案

Hash1继承自 Singleton<Hash1>是隐式私有(private)的。将其更改为

class Hash1 : public IHash, public Singleton<Hash1> {

关于模板化单例的 C++ 工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207439/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com