【发布时间】: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