【问题标题】:C++ Constructor Overload Resolution with Multiple Inheritance具有多重继承的 C++ 构造函数重载解决方案
【发布时间】: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++ 标准中有一个部分将复制构造函数定义为比用户定义的构造函数更好的匹配*?否则我的假设是,如果不存在有利于复制构造函数的规则,那么编译器要么按照继承顺序(与多重继承的构造顺序一样),要么只是给我一个模棱两可的构造函数调用错误。但是,颠倒DerivedBaseOther 继承的顺序并不会改变输出,这让我相信我对复制构造函数的最初猜测是正确的。谁能指出决定我所看到的行为的规则?

* 我检查了cppreference.com's Overload Resolution page,但我没有看到那里列出的任何规则可以解释我所看到的行为(尽管我 标准语不完全流利,所以我很容易错过)。

【问题讨论】:

  • 对 clang/gcc Demo987654322@的模糊调用
  • 编译器中的不明确调用,无法编译。
  • 嗯,有趣。我正在使用 Visual Studio 2017.3(预览版),它甚至可以使用 /permissive- 标志进行编译。我假设这是 Visual Studio 的非标准行为,而不是 Clang/GCC 的非标准行为?
  • 是的,它在 VC++ 上编译成功。观看现场演示here

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


【解决方案1】:

有问题的代码 sn-p 编译的原因是由于 Visual Studio 的不符合标准的行为(我目前正在使用 VS2017.3 Preview,即使使用 /permissive- 标志编译代码也不会出错) .下面是 GCC 和 Clang 发出的错误:

海合会

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/

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2015-03-24
    • 2014-08-21
    相关资源
    最近更新 更多