小编DFS*_*dow的帖子

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

我有这么短的代码片段,我希望得到更多关于为什么重载决策选择一个构造函数而不是另一个构造函数的信息.这是有问题的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

*我查看了cppreference.com的Overload Resolution页面,但我没有看到任何列出的规则可以解释我所看到的行为(虽然我不能完全熟悉Standardese,所以我很容易错过它).

c++ inheritance constructor multiple-inheritance overload-resolution

5
推荐指数
1
解决办法
298
查看次数