关闭

关于基类和派生类的动态绑定问题

标签: c++
49人阅读 评论(0) 收藏 举报
分类:

关于基类和派生类的动态绑定问题

Example 1

Quote是基类

class Quote
{
public:
    //constructor and other member function
    virtual std::ostream& debug (std::ostream& os)
     {
         os << bookNo << " " << price << " ";
         return os;
     }
//member data
private: 
}

Bulk_quote是派生类

class Bulk_quote : public Quote
{
public:
    // constructor
    std::ostream& debug(std::ostream& os) override
    {
        Quote::debug(os) << quantity << " " << discount;
        return os;
    }
};
int main()
{
    Quote a("12232", 12.3);
    Bulk_quote b("3344", 22.2, 8, 0.13);
//    Disc_quote c;
    Quote *p1 = &a;
    Quote *p2 = &b;
    Quote &pt1 = a;
    Quote &pt2 = b;
    ///////////////////////
    a.debug(std::cout)<< endl;
    b.debug(std::cout)<< endl;
    p1->debug(std::cout)<< endl;
    p2->debug(std::cout)<< endl;
    pt1.debug(std::cout)<< endl;
    pt2.debug(std::cout)<< endl;
}

运行结果

  • p2和pt2的静态类型是基类的指针或者引用,但是被指向或者绑定在了派生类上,而debug()成员函数是virtual function, 所以在用指针和引用的时候编译器就要判断选择基类还是派生类

Example 2

class Base
{
public:
    virtual void fn1 () {std::cout << "Base::fn1() operated" << std::endl;}
    void fn2() {std::cout << "Base::fn2() operated" << std::endl;}
};

class Derived: public Base
{
public:
    void fn1() override {std::cout << "Derived::fn1() operated" << std::endl;}
    void fn2() {std::cout << "Derived::fn2() operated" << std::endl;}
};
int main()
{
    Derived der;
    Derived *der_ptr;
    Base *base_ptr;
    der_ptr = &der;
    base_ptr = &der;
    der_ptr->fn1();
    der_ptr->fn2();
    base_ptr->fn1();
    base_ptr->fn2();
}

运行结果

这里写图片描述

  • 动态绑定只对virtual function 有用,由于fn2 是基类中的普通成员函数, 则 base_ptr 虽然指向一个派生类,其调用的函数还是派生类对象中的基类部分中的成员函数
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1101次
    • 积分:119
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档