基础构造函数的 using
声明是私有(private)的,但仍然可以构造该类。为什么?
对于 operator[]
的 using
声明,辅助功能的工作方式不同,必须公开。
#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];
}
如果我希望构造函数是私有(private)的怎么办?可以用 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.
如果您希望“继承”的构造函数是私有(private)的,则必须手动指定构造函数。您不能使用 using 声明来执行此操作。
关于c++ - 私有(private)使用基构造函数的声明不是私有(private)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164121/