DFS*_*dow 5 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;
}
Run Code Online (Sandbox Code Playgroud)
我假设C++标准中有一节将复制构造函数定义为比用户定义的构造函数更好的匹配*?我的另一个假设是,如果没有任何规则支持复制构造函数,那么编译器要么按照继承的顺序(如同具有多重继承的构造顺序),要么只是给我一个模糊的构造函数调用错误.但是,颠倒了Derived继承Base和Other不改变输出的顺序,这让我相信我最初关于复制构造函数的猜测是正确的.任何人都能指出我决定我所看到的行为的规则吗?
*我查看了cppreference.com的Overload Resolution页面,但我没有看到任何列出的规则可以解释我所看到的行为(虽然我不能完全熟悉Standardese,所以我很容易错过它).
有问题的代码片段编译的原因是 Visual Studio 的非标准一致行为(我当前使用 VS2017.3 预览版,即使使用 /permissive- 标志,它也会编译代码而不会出现错误)。以下是 GCC 和 Clang 发出的错误:
\n\nError(s):\nsource_file.cpp: In constructor \xe2\x80\x98Derived::Derived()\xe2\x80\x99:\nsource_file.cpp:25:20: error: call of overloaded \xe2\x80\x98Other(Derived&)\xe2\x80\x99 is ambiguous\n Other(*this)\n ^\nsource_file.cpp:16:5: note: candidate: Other::Other(const Base&)\n Other(const Base&)\n ^\nsource_file.cpp:12:5: note: candidate: Other::Other(const Other&)\n Other(const Other&)\n ^\nRun Code Online (Sandbox Code Playgroud)\n\nError(s):\nsource_file.cpp:25:9: error: call to constructor of \'Other\' is ambiguous\n Other(*this)\n ^ ~~~~~\nsource_file.cpp:12:5: note: candidate constructor\n Other(const Other&)\n ^\nsource_file.cpp:16:5: note: candidate constructor\n Other(const Base&)\n ^\n1 error generated.\nRun Code Online (Sandbox Code Playgroud)\n\n错误输出取自http://rextester.com/。
\n