【问题标题】:Why Derrived pointer binds statically to derived object?为什么 Derrived 指针静态绑定到派生对象?
【发布时间】:2023-02-26 03:38:35
【问题描述】:

在附加的代码中为什么: p1->打印();动态绑定? 为什么: p2->打印(); 静态绑定?

#include<iostream>

class Base{   public:

virtual void print() 
{     std::cout<<"Base"<<std::endl;}  
    
};

class Derived : public Base{
public:

virtual void print()
{    std::cout<<"Derived"<<std::endl; }  
};
int main()
{
    Base *p1 = new Base{ } ;
     
    p1->print();
     
    std::cout<<"------------------"<<std::endl; 
    Derived *p2 = new Derived{ } ;    
   
    p2->print();
    
    return 0;
}

据我所知,如果指针或引用的类型与指针或引用指向的对象类型不同并且必须有一个虚函数来激活动态绑定,则虚函数将动态绑定。

【问题讨论】:

    标签: c++ class pointers virtual bounding


    【解决方案1】:

    根据指针的静态类型在类中搜索函数print

    Base *p1 = new Base{ } ;
     
    p1->print();
     
    Derived *p2 = new Derived{ } ; 
    
    p2->print();   
    

    因为在类Base中查找函数print时,指针p1的静态类型为Base *。

    另一方面,由于指针p2的静态类型是Derived *,因此在类Derived中搜索函数print。

    你可以写例如

    Base *p3 = new Derived{};
    
    p3->print();
    

    在这种情况下,由于指针 p3 的静态类型是 Base *,因此将在类 Base 中搜索函数 print。但是由于指针的动态类型是Derived *,那么会调用派生类的函数print。

    【讨论】:

      【解决方案2】:

      两个电话是动态绑定它对您的示例没有影响。

      动态绑定意味着将根据指向对象的动态运行时类型而不是指向它的指针的静态类型来解析调用。但是,在您的示例中,这两种类型是相同的,因此结果将是相同的。

      动态绑定仅在对象的静态类型为不同的从指向它的指针的类型。例如:

      Base* p3 = new Derived{};
      p3->print();
      

      即使p3 的静态类型是Base*,这也会打印“Derived”,因为指向的对象的动态类型是Derived。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-10
        • 2012-03-14
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-23
        • 2011-09-04
        相关资源
        最近更新 更多