为什么需要使用声明命名构造函数
Why the need for a using-declaration naming a constructor?
C++11标准中的7.3.3.p1和p3两段都使用命名构造函数的声明引用了。为什么这是必要的?下面的代码显示了基类A
的构造函数如预期的那样出现在派生类B
中。
class A
{
int i;
public:
A() : i(0) {}
A(int i) : i(i) {}
};
class B : public A
{
public:
// using A::A;
A f1() { return A(); }
A f2() { return A(1); }
};
int main()
{
B b;
A a1 = b.f1();
A a2 = b.f2();
}
如果我在上面注释掉using A::A;
,则程序执行中没有任何变化。
这意味着从父类继承非默认构造函数,在本例中为A(int i)
。主要更改您的申报,如:
int main()
{
B b(42); // Want to forward this to A::A(int)
...
}
如果没有using A::A
子句,您将得到以下编译器错误(至少来自g++4.8.0):
co.cpp: In function ‘int main()’:
co.cpp:20:11: error: no matching function for call to ‘B::B(int)’
B b(42);
^
co.cpp:20:11: note: candidates are:
co.cpp:10:7: note: B::B()
class B : public A
^
co.cpp:10:7: note: candidate expects 0 arguments, 1 provided
co.cpp:10:7: note: constexpr B::B(const B&)
co.cpp:10:7: note: no known conversion for argument 1 from ‘int’ to ‘const B&’
co.cpp:10:7: note: constexpr B::B(B&&)
co.cpp:10:7: note: no known conversion for argument 1 from ‘int’ to ‘B&&’
但是,如果您将using A::A
声明添加回来,它会干净地编译。CCD_ 7最终调用CCD_ 8。
相关文章:
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 将派生类的构造函数声明为父类的友元
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何使用构造函数声明指向用户定义对象的指针?
- 如何从构造函数声明新的私有变量?
- 根据二手构造函数声明成员
- 如何用类别的consumetrized构造函数声明使用类的比较对象设置的STL设置
- C++.奇怪的构造函数声明
- 使用ctags查找用c++中的构造函数声明的变量
- 将构造函数声明为private会显示错误.是否至少有一个公共构造函数是必需的
- 如何在C++中使用带参数的构造函数声明具有来自另一个类的类数据的对象
- 在构造函数声明中编写模板类型的参数列表是否有效?
- 在另一个类中使用自定义构造函数声明一个类
- 谷歌测试-构造函数声明错误
- 使用构造函数声明作为虚函数
- 无效地使用不完整的类型模板构造函数声明
- 将构造函数声明为显式时出现编译错误
- 它在构造函数声明中意味着什么
- 类构造函数声明了两次
- 有一种方法可以使用默认的复制构造函数声明复制构造函数非公共和?