今作成しているプログラムでシングルトンパターンを持つ基底クラスを継承したクラスを作る必要が出てきたので,こちらのサイト(http://glass5er.hatenablog.com/entry/20130630/1372556362))を参考にしていたのですが,このサイトで扱われているソースコードに対して1つ疑問があったので質問しました.
サイトのソースコードは以下のようになっています.
lang
1#include <iostream> 2#include <string> 3 4using namespace std; 5 6//---------------- 7 8template <class U> 9class SingletonParent 10{ 11 public: 12 static U* getInstance() { 13 static U instance; 14 return &instance; 15 } 16 17 protected: 18 //-- template func in template class available 19 template<typename T> void print2Times(T v); 20 21 SingletonParent() { 22 base_str = string("BASE"); 23 } 24 virtual ~SingletonParent() {} 25 string base_str; 26}; 27 28 29//-- use template succession 30class SingletonChild : public SingletonParent<SingletonChild> { 31 public: 32 SingletonChild() { 33 child_value = 0; 34 } 35 ~SingletonChild() {} 36 37 void set(int v) { child_value = v; } 38 int get() { return child_value; } 39 40 void print() { 41 print2Times(base_str); 42 print2Times(child_value); 43 } 44 private: 45 int child_value; 46}; 47 48//-- when defining template func in template class, 49//-- 2 template declaraton required 50template<class U> template<typename T> 51void 52SingletonParent<U>::print2Times(T v) 53{ 54 cout << v << v << endl; 55} 56 57 58//---------------- 59 60 61int 62main(int argc, char const* argv[]) 63{ 64 //-- actually the same instance 65 SingletonChild *inst1 = SingletonChild::getInstance(); 66 SingletonChild *inst2 = SingletonChild::getInstance(); 67 68 //-- both 0 69 cout << inst1->get() << endl; 70 cout << inst2->get() << endl; 71 72 //-- BASEBASE, 00 73 inst1->print(); 74 75 inst2->set(3); 76 77 //-- both 3 78 cout << inst1->get() << endl; 79 cout << inst2->get() << endl; 80 81 //-- BASEBASE, 33 82 inst1->print(); 83 return 0; 84} 85
派生クラスのコンストラクタがpublicになっているので,これではシングルトンの意味がないと思い,privateに変更したところ,下記のようにSingletonChildのコンストラクタがprivateだからアクセスできないと怒られました...
私としては,基底クラスから継承したgetInstance()を使って派生クラスの内部からSingletonChild()にアクセスしているので,問題ないと考えていたのですが,どのあたりが間違っているのでしょうか?
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/main.d" -MT"src/main.d" -o "src/main.o" "../src/main.cpp"
../src/main.cpp: In instantiation of ‘static U* SingletonParent<U>::getInstance() [with U = SingletonChild]’:
../src/main.cpp:93:43: required from here
../src/main.cpp:70:5: error: ‘SingletonChild::SingletonChild()’ is private
SingletonChild() {
^
../src/main.cpp:40:16: error: within this context
static U instance;
^
make: *** [src/main.o] エラー 1
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/05/05 06:00