代码之家  ›  专栏  ›  技术社区  ›  Rick Jim DeLaHunt

为什么指向基类的派生类指针可以调用派生类成员函数?[复制]

  •  0
  • Rick Jim DeLaHunt  · 技术社区  · 4 年前
    #include <iostream>
    using namespace std;
    
    struct Base {
        void doBase() {
            cout << "bar" << endl;
        }
    };
    
    struct Derived : public Base {
        void doBar() {
            cout << "bar" << endl;
       }
    };
    
    int main()
    {
        Base b;
        Base* b_ptr = &b;
        Derived* d_ptr = static_cast<Derived*>(b_ptr);
        d_ptr->doBar(); //Why there is no compile error or runtime error?
        return 0;
    }
    

    bar\n .

    d_ptr 实际上,它在调用派生类成员函数时指向基类。

    这是一种未定义的行为还是其他什么?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Eugene    4 年前

    static_cast -这是一种告诉编译器“我比你更了解类型”的方法。你说你的目标是 Derived . 你对编译器撒谎了-这就是未定义的行为。

    它碰巧起作用是因为 doBar() 衍生的

    推荐文章