【c++】動態綁定


C++的函數調用默認不使用動態綁定。要觸發動態綁定,必須滿足兩個條件:

  1. 只有指定為虛函數的成員函數才能進行動態綁定
  2. 必須通過基類類型的引用或指針進行函數調用

因為每個派生類對象中都擁有基類部分,所以可以使用基類類型的指針或引用來引用派生類對象

示例

#include <iostream>
#include <string>
using namespace std;

struct base
{
    base(string str = "Base") : basename(str) {}
    virtual void print() { cout << basename << endl; }
    private:
        string basename;
};
struct derived : public base
{
    derived(string str = "Derived") : derivedname(str) {}
    void print() { cout << derivedname << endl; }
    private:
        string  derivedname;
};

int main()
{
    base b;
    derived d;
    cout << "b.print(), d.print()" << endl;
    b.print();
    d.print();

    base *pb = &b;
    base *pd = &d;
    cout << "pb->print(), pd->print()" << endl;
    pb->print();
    pd->print();

    base &yb = b;
    base &yd = d;
    cout << "yb.print(), yd.print()" << endl;
    yb.print();
    yd.print();
}

結果

 分析

可以看出基類類型的指針或引用來引用派生類對象時,調用的是重定義的虛函數。要想覆蓋虛函數機制,調用基函數的版本,可以使用強制措施。例:

代碼

#include <iostream>
#include <string>
using namespace std;

struct base
{
    base(string str = "Base") : basename(str) {}
    virtual void print() { cout << basename << endl; }
    private:
        string basename;
};
struct derived : public base
{
    derived(string str = "Derived") : derivedname(str) {}
    void print() { cout << derivedname << endl; }
    private:
        string  derivedname;
};

int main()
{
    base b;
    derived d;
    cout << "b.print(), d.print()" << endl;
    b.print();
    d.base::print();

    base *pb = &b;
    base *pd = &d;
    cout << "pb->print(), pd->print()" << endl;
    pb->print();
    pd->base::print();

    base &yb = b;
    base &yd = d;
    cout << "yb.print(), yd.print()" << endl;
    yb.print();
    yd.base::print();
}

結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM