c++ - 私有(private)使用基构造函数的声明不是私有(private)的

标签 c++ inheritance constructor using-declaration

基础构造函数的 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/

相关文章:

c# - 通过构造函数使用主键初始化 EF(6) 对象(最佳实践?)

c++ - C编程,数组打印不正确

c++ - MFC数据通过PostMessage转发到主线程

c++ - 在 OpenGL 中将深度渲染到纹理时出现奇怪的结果

c++ - 无法获取输出 union 集

java - 更改 java 8 默认方法的可见性

javascript - 在 AngularJS 指令中实现继承

c# - 会自动调用基类构造函数吗?

java - 构造函数中的对象参数

c++ - 错误 : Conversion from derived* to base&