显式构造函数由派生类隐式调用
C++: explicit constructor is implicitly called by derived class
为什么使构造函数显式不能阻止它被派生类隐式调用?
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;
}
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素