簡體   English   中英

構造函數中的C ++虛函數

[英]C++ virtual function in constructor

我正在閱讀關於c ++構造函數的這篇文章

我們建議您在構造函數中調用虛函數時要小心。 因為始終在派生類構造函數之前調用基類構造函數,所以在基礎構造函數中調用的函數是基類版本,而不是派生類版本。 在下面的示例中,構造DerivedClass導致print_it()的BaseClass實現在DerivedClass構造函數導致執行print_it()的DerivedClass之前執行:

這個例子:

    class BaseClass {
    public:
        BaseClass() {
            print_it();
        }
        virtual void print_it() {
            cout << "BaseClass print_it" << endl;
        }
    };

    class DerivedClass : public BaseClass {
    public:
        DerivedClass() {
            print_it();
        }
        virtual void print_it() {
            cout << "Derived Class print_it" << endl;
        }
    };

    int main() {

        DerivedClass dc;
    }

這是輸出:

BaseClass print_it
Derived Class print_it

我嘗試了這段代碼,輸出如上所述 但是我也嘗試了沒有virtual關鍵字的相同示例:

    class BaseClass {
    public:
        BaseClass() {
            print_it();
        }
        void print_it() {
            cout << "BaseClass print_it" << endl;
        }
    };

    class DerivedClass : public BaseClass {
    public:
        DerivedClass() {
            print_it();
        }
        void print_it() {
            cout << "Derived Class print_it" << endl;
        }
    };

    int main() {

        DerivedClass dc;
    }

並得到了相同的結果

那么有什么不同,他們警告的危險是什么?

@marked重復:

這個問題是不同的,因為consturctors都調用虛方法而不是一個調用虛方法的構造函數。

沒有區別。 這就是危險。

如果你不知道更好,那么你可能會期望這樣:

Derived Class print_it
Derived Class print_it

期望是因為如果從Base函數調用virtual print_it() ,多態意味着您通常會獲得Derived版本。

但是,當您在Base構造函數中編寫它時,對象的Base部分仍在構建中,並且正在構造的對象的“動態類型”仍然是Base ,而不是Derived 所以你沒有得到通常的多態行為。

這篇文章警告你這個事實。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM