C++继承中的静态指针

Joh*_*hnX 4 c++ polymorphism singleton pointers static-members

我为什么p->a()打电话感到困惑B::a()?C++文档/标准中是否有一个段落可以很好地描述这种行为?

#include <iostream>
using namespace std;

class A {
  public:
  A() { cout << "A ctor" << endl; a_instance = this; }
  static A *get_instance() { return a_instance; }
  static A *a_instance;
  void virtual a() { cout << "From base class" << endl; }
};

class B : public A {
public:
  B() { cout << "B ctor" << endl; b_instance = this; }
  static B *get_instance() { return b_instance; }
  static B *b_instance;
  void virtual a() { cout << "From derived class" << endl; }
};

A *A::a_instance = 0;
B *B::b_instance = 0;

main()
{
    cout << "Create A" << endl;
    A ab;
    cout << "Create B" << endl;
    B abc;
    B *ptr = B::get_instance();
    A *p = A::get_instance();

    cout << "Called from A object type" << endl;
    if (p) {
       p->a();
    }
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rop 6

创建变量时abc,A构造函数设置a_instance为该实例.尽管p是一个指针A,因为实例指向a B,它正确调用B::a().

若要解决此问题,您可以使用以下内容:

A* A::get_instance()
{
    static A a;
    return &a;
}

B* B::get_instance()
{
    static B b;
    return &b;
}  
Run Code Online (Sandbox Code Playgroud)

并删除所有与a_instance和有关的代码b_instance.


Mar*_*som 5

B构造函数调用的A第一个构造函数.这取代了a_instance你已经创建的那个.

构造函数的这种链接在标准中有明确的定义.始终首先调用基类,以便保证派生的构造函数在有效的基础对象上工作.