显式构造函数由派生类隐式调用

C++: explicit constructor is implicitly called by derived class

本文关键字:调用 构造函数 派生      更新时间:2023-10-16

为什么使构造函数显式不能阻止它被派生类隐式调用?

class A{
public:
    explicit A(){}
};
class B : public A{
public:
    B(){ //Constructor A() is called implicitly
        //...
    }
}

在我的程序中有一种情况,我宁愿有编译错误,在这种情况下,它将节省我大量的时间来寻找一个错误。现在我改变了A的默认构造函数,以接受一个虚拟的"int"参数来实现这一点,但是"显式"关键字不应该为此工作吗?

g++-4.8编译上述代码时没有出现任何错误或警告。

您对explicit关键字的假设是错误的

explicit关键字不是为了防止从派生类调用构造函数,而是为了防止隐式转换,例如下面的示例:https://stackoverflow.com/a/121163/1938163

我在这里总结一下相关的部分:

class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }
  int GetFoo () { return m_foo; }
private:
  int m_foo;
};

由于最多只能进行一次隐式转换来解决歧义,如果您有一个像

这样的函数
void DoBar (Foo foo)
{
  int i = foo.GetFoo();
}

下面是合法的:

int main ()
{
  DoBar (42); // Implicit conversion
}

这正是显式关键字发挥作用的地方:禁止上面的情况。

为了解决你的问题,为了防止你的类被用作基类,只要用final标记构造函数,如果你使用c++ 11 (http://en.wikipedia.org/wiki/C++11#Explicit_overrides_and_final)

explicit关键字通常用于只有一个形参的构造函数。它防止了从形参类型到类类型的对象的隐式构造。

下面的例子可以编译,它通常不是你想要的:

#include <iostream>
using namespace std;
struct Test
{
    Test(int t) {}
};
void test_fun(Test t) {}
int main() {
    test_fun(1); //implicit conversion
    return 0;
}

使用显式关键字,此示例将无法编译:

#include <iostream>
using namespace std;
struct Test
{
    explicit Test(int t) {}
};
void test_fun(Test t) {}
int main() {
    test_fun(1); //no implicit conversion, compiler error
    return 0;
}