【发布时间】:2017-12-30 14:53:46
【问题描述】:
我有这个简短的 sn-p 代码,我想了解更多关于为什么重载决议选择一个构造函数而不是另一个构造函数的信息。这是有问题的代码:
#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 从Base 和Other 继承的顺序并不会改变输出,这让我相信我对复制构造函数的最初猜测是正确的。谁能指出决定我所看到的行为的规则?
* 我检查了cppreference.com's Overload Resolution page,但我没有看到那里列出的任何规则可以解释我所看到的行为(尽管我 标准语不完全流利,所以我很容易错过)。
【问题讨论】:
标签: c++ inheritance constructor multiple-inheritance overload-resolution