重庆专业网站建设公司哪家好,seo的中文意思是什么,公司域名让做网站的,国家军事新闻头条C多态之动态绑定#xff1a; 1、概念#xff1a;在程序执行期间(非编译期)判断所引用对象的实际类型#xff0c;根据其实际类型调用相应的方法。
使用virtual关键字修饰类的成员函数时#xff0c;指明该函数为虚函数#xff0c;派生类需要重新实现#xff0c;编译器将实…C多态之动态绑定 1、概念在程序执行期间(非编译期)判断所引用对象的实际类型根据其实际类型调用相应的方法。
使用virtual关键字修饰类的成员函数时指明该函数为虚函数派生类需要重新实现编译器将实现动态绑定。
2、条件a必须是虚函数。 b通过基类类型的引用或者指针调用虚函数。 class Base
{
public: Base() { coutBase:: Base()endl; } ~Base() { coutBase::~Base()endl; } virtual void Test1() { coutBase:: Test1()endl; } int sum(int a, int b) { coutBase:: sum abendl; return ab; }
}; class Derived:public Base
{
public: Derived() { coutDerived::Derived()endl; } ~Derived() { coutDerived::~Derived()endl; }
protected: //基类为public virtual void Test1() { coutDerived:: Test1()endl; } virtual int sum(int a, int b) { coutDerived:: sum abendl; return ab; } }; void FunTest1(Base b) //通过基类的指针或引用访问派生类的成员
{ b.Test1();
} void FunTest()
{ Derived d; Base b; Base pBase d; FunTest1(b); FunTest1(d); coutsum pBase.sum(1,2)endl;
} 当修改了派生类中重写的虚函数与原来的返回值不同编译器报错。 故重写覆盖要求具有相同的参数和返回值。而这个规则对于协变则会放松。 3、协变
在C中只要原来的返回类型是基类类型的指针或引用新的返回值类型是派生类的指针或引用覆盖的方法就可以改变返回类型这样的返回类型称为协变返回类型。
class Base
{
public: Base() { coutBase:: Base()endl; } ~Base() { coutBase::~Base()endl; } virtual Base operator(const Base b) { coutBase::operator(const Base b)endl; return *this; } }; class Derived:public Base
{
public: Derived() { coutDerived:: Derived()endl; } ~Derived() { coutDerived::~Derived()endl; } virtual Derived operator(const Base b) { coutDerived::operator(const Base b)endl; return *this; } }; void FunTest()
{ Derived d1,d2; Base b; Base pBase d1; pBase.operator(d2); } 协变返回类型的优势在于总是可以在适当程度的抽象层面工作。目前一般认为返回值可以协变参数则不可以。 因此在C标准的虚函数中返回值协变参数不变。