基础构造函数的using声明是私有的,但仍然可以构造该类.为什么?
可访问性对于operator []使用必须公开的声明的工作方式不同.
#include <vector> template<typename T> class Vec : std::vector<T> { private: using std::vector<T>::vector; // Works,even if private. Why? public: using std::vector<T>::operator[]; // must be public }; int main(){ Vec<int> vec = {2,2}; auto test = vec[1]; }
如果我希望构造函数是私有的,该怎么办?是否可以使用声明来完成?
解决方法
无论基类的可访问性如何,基类构造函数的using声明都保持与基类相同的可访问性.从
[namespace.udecl]开始:
A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead,the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class,and the accessibility of the using-declaration is ignored
重点补充
用简单的英语,from cppreference:
It has the same access as the corresponding base constructor.