这是一个简单的C ++项目,具有两种设计模式:单例和工厂,sigleton也是模板化类,还包括接口(IHash)和类(Hash1)。
一个简单的工厂类(HashFactory)创建一个sigleton(Hash1); Hash1继承了接口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;
}

最佳答案

Hash1Singleton<Hash1>的继承是隐式私有的。更改为

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

10-06 01:07