c++中的动态联编

在c++中的动态联编是通过虚函数来实现,但在调用时 , 必须用引用、指针才能实现动态联编

例子如下:

指针调用

#include <iostream>

using namespace std;

const double pi = 3.14;

class A
{
public:
    A() {};
    virtual double area() const {return 0.0;}

};

class B:public A
{
public:
    B(double myr)  {R = myr;}
    virtual double area()  const {return pi*R*R;}
private:
    double R;


};


int main()
{

    A *fig;

    B c(3.0);
    cout<<"Area of B is  ";
    fig = &c;
    cout<<fig->area()<<endl;


    return 0;
}

c++中的动态联编


普通变量调用

#include <iostream>

using namespace std;

const double pi = 3.14;

class A
{
public:
    A() {};
    virtual double area() const {return 0.0;}

};

class B:public A
{
public:
    B(double myr)  {R = myr;}
    virtual double area()  const {return pi*R*R;}
private:
    double R;


};


int main()
{

    A fig;

    B c(3.0);
    cout<<"Area of B is  ";
    fig = c;
    cout<<fig.area()<<endl;


    return 0;
}

c++中的动态联编

c++中的动态联编,布布扣,bubuko.com

c++中的动态联编

上一篇:Spring:Spring 中集成JPA;


下一篇:Java生成图片验证码(有点仿QQ验证码的意思)