【发布时间】:2019-02-05 22:24:09
【问题描述】:
我正在尝试运行以下代码,但出现错误。
#include <iostream>
template <typename T>
class Base {
public :
static T& Get() {
static T t;
return t;
}
};
class Derived : public Base<Derived> {
private :
Derived() {}
// friend Base<Derived>; //un-commenting this will make code work.
};
int main() {
Derived& d = Derived::Get();
return 0;
}
错误:
prog.cpp:在“静态 T& Base::Get() [with T = Derived]”的实例化中:
prog.cpp:18:24: 从这里需要
prog.cpp:7:14:错误:“Derived::Derived()”在此上下文中是私有的
静态 T t;
^
prog.cpp:14:4: 注意:这里声明为私有
派生(){}
^~~~~~~
我有以下问题
-
Derived类公开派生自Base类,难道Get()也是Derived 的成员函数吗? - 如果 [1] 为真,并且
Get()成为Derived的成员函数,则 为什么不能调用Derived的私有构造函数。 - 假设我们有多个类要实现为单例,是 有一种方法可以使用类似的模板来做到这一点 上面的例子? (附加问题)
我明白了:
- 我们可以通过让 base 成为派生的朋友来使上面的代码工作 代码行。
- 我们可以将
Get()设为“非静态虚函数”并覆盖 派生类。
我不是在寻找上述解决方案。不过,如果这(这些)是实现这种设计的唯一可能解决方案,请告诉我。
【问题讨论】:
标签: c++ templates inheritance compiler-errors singleton