簡體   English   中英

具有多重繼承的C ++構造函數重載決策

[英]C++ Constructor Overload Resolution with Multiple Inheritance

我有這么短的代碼片段,我希望得到更多關於為什么重載決策選擇一個構造函數而不是另一個構造函數的信息。 這是有問題的代碼:

#include <iostream>

struct Base
{

};

struct Other
{
    Other(const Other&)
    {
        std::cout << "Copy Constructor\n";
    }
    Other(const Base&)
    {
        std::cout << "Custom Constructor\n";
    }
};

struct Derived : public Base, public Other
{
    Derived() :
        Other(*this)
    {

    }
};

int main()
{
    Derived derived;    // Prints "Copy Constructor"

    system("pause");
    return 0;
}

我假設C ++標准中有一節將復制構造函數定義為比用戶定義的構造函數更好的匹配*? 我的另一個假設是,如果沒有任何規則支持復制構造函數,那么編譯器要么按照繼承的順序(如同具有多重繼承的構造順序),要么只是給我一個模糊的構造函數調用錯誤。 但是,顛倒DerivedBaseOther繼承的順序不會改變輸出,這使我相信我最初關於復制構造函數的猜測是正確的。 任何人都能指出我決定我所看到的行為的規則嗎?

*我查看了cppreference.com的Overload Resolution頁面 ,但我沒有看到任何列出的規則可以解釋我所看到的行為(雖然我不能完全熟悉Standardese,所以我很容易錯過它)。

有問題的代碼片段編譯的原因是由於Visual Studio的非標准符合行為(我目前正在使用VS2017.3預覽版,即使使用/ permissive-標志也可以編譯代碼而不會出現錯誤)。 以下是GCC和Clang發出的錯誤:

GCC

Error(s):
source_file.cpp: In constructor ‘Derived::Derived()’:
source_file.cpp:25:20: error: call of overloaded ‘Other(Derived&)’ is ambiguous
         Other(*this)
                    ^
source_file.cpp:16:5: note: candidate: Other::Other(const Base&)
     Other(const Base&)
     ^
source_file.cpp:12:5: note: candidate: Other::Other(const Other&)
     Other(const Other&)
     ^

Error(s):
source_file.cpp:25:9: error: call to constructor of 'Other' is ambiguous
        Other(*this)
        ^     ~~~~~
source_file.cpp:12:5: note: candidate constructor
    Other(const Other&)
    ^
source_file.cpp:16:5: note: candidate constructor
    Other(const Base&)
    ^
1 error generated.

http://rextester.com/獲取錯誤輸出。

暫無
暫無

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

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