具有多重继承的C ++构造函数重载决策

时间:2017-07-24 21:34:02

标签: c++ inheritance constructor multiple-inheritance overload-resolution

我已经获得了这段简短的代码片段,我想了解更多关于为什么重载决策选择一个构造函数而不是另一个构造函数的信息。这是相关代码:

#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 ++标准中有一节将拷贝构造函数定义为比用户定义的构造函数更好的匹配*?我的另一个假设是,如果没有任何规则支持复制构造函数,那么编译器要么按照继承的顺序(如同具有多重继承的构造顺序),要么只是给我一个模糊的构造函数调用错误。但是,颠倒Derived继承自BaseOther的顺序并不会改变输出,这让我相信我最初对有关复制构造函数的猜测是正确的。任何人都可以指出我决定我所看到的行为的规则吗?

*我查了cppreference.com's Overload Resolution page,但我没有看到那里列出的任何规则可以解释我所看到的行为(虽然我是 没有完全流利的Standardese,所以我很容易错过它。)

1 个答案:

答案 0 :(得分:1)

有问题的代码片段编译的原因是由于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/获取错误输出。

相关问题