如果基 class 被继承 public,基 class 的 public 静态函数是否会成为派生 class 的成员函数?

Does public static functions of base class become member functions of derived class if base class is inherited publicly?

我正在尝试 运行 以下代码但出现错误。

#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;
}

Error :

prog.cpp: In instantiation of ‘static T& Base::Get() [with T = Derived]’:
prog.cpp:18:24: required from here
prog.cpp:7:14: error: ‘Derived::Derived()’ is private within this context
static T t;
^
prog.cpp:14:4: note: declared private here
Derived() {}
^~~~~~~

我有以下问题

  1. class Derived 是从 class Base 公开派生的,它不也使 Get() 成为 Derived 的成员函数吗?
  2. 若[1]为真,且Get()成为Derived的成员函数,则 为什么它不能调用 Derived.
  3. 的私有构造函数
  4. 假设我们有多个 classes 被实现为 Singleton,是 有一种方法我们可以使用类似于以下内容的模板来做到这一点 上面的例子? (附加问题)

我明白了:

我不是在寻找上述解决方案。不过,如果这个(这些)是实现这种设计的唯一可能解决方案,请告诉我。

class Derived is publically derived from class Base, doesn't it makes Get() a member function of Derived too ?

从某种意义上说是的,查找 Derived::Get() 将起作用,但它调用的函数与您编写 Base<Derived>::Get().

时调用的函数完全相同

If [1] is true, and Get() becomes a member function of Derived, then why it's not able to call the private constructor of Derived.

因为不同类不能通过名称访问私有成员。这就是 private 的用途。 Derived 无法访问 Base.

的私有成员的原因相同

Assume we have multiple classes to be implemented as Singleton, is there a way we can do it using templates with something similar to the above example? (additional question)

这不是您的示例所做的吗?

We can make the above code work by making base a friend of derived line to the code.

正确。

We can make Get() as "non static virtual function" and override in the derived classes.

我不这么认为。你不能在没有对象的情况下调用该虚函数。您需要在调用 Get 之前创建 Derived 的实例,但是 Get 应该创建我们的对象。

Though, please let me know if this(these) is(are) the only possible solutions to achieve this kind of design.

我可能会去交朋友。简单,简洁,做你想做的。还有其他解决方案,例如在基类中使用受保护类型,并定义接收该受保护类型的 public 构造函数,但这非常容易泄漏,我不推荐。

  1. class Derived is publically derived from class Base, doesn't it makes Get() a member function of Derived too ?

没有。 base 的成员函数(静态和非静态)是 base 的成员函数,而不是派生的成员函数 class。但是,调用成员函数时会查找 base(s) 的成员函数(取决于可见性)。