您可以使用 using 将基 class 中的 public 成员重新声明为派生 class 中的私有成员吗?
Can you use using to redeclare a public member in base class as private in derived class?
此代码片段演示了如何更改 class 成员访问权限,来自 IBM。
struct A {
protected:
int y;
public:
int z;
};
struct B : private A { };
struct C : private A {
public:
using A::y;
using A::z;
};
struct D : private A {
protected:
using A::y;
using A::z;
};
struct E : D {
void f() {
y = 1;
z = 2;
}
};
struct F : A {
public:
using A::y;
private:
using A::z;
};
int main() {
B obj_B;
// obj_B.y = 3;
// obj_B.z = 4;
C obj_C;
obj_C.y = 5;
obj_C.z = 6;
D obj_D;
// obj_D.y = 7;
// obj_D.z = 8;
F obj_F;
obj_F.y = 9;
obj_F.z = 10;
}
根据文章,修改obj_F.z
是允许的,因为F
class中的using
声明没有生效,因此,F::z
仍然是 public
.
但是,当我将其插入 Compiler Explorer 时,它无法编译,说 F::z
是 private
。这是怎么回事?
这篇文章似乎有误。它说,
You cannot restrict the access to x with a using declaration.
但是我在标准中找不到这样的说法。 [namespace.udecl]/19
A synonym created by a using-declaration has the usual accessibility
for a member-declaration.
[ Example:
class A {
private:
void f(char);
public:
void f(int);
protected:
void g();
};
class B : public A {
using A::f; // error: A::f(char) is inaccessible
public:
using A::g; // B::g is a public synonym for A::g
};
— end example ]
即使这个例子也在增加可访问性,但标准并没有说不能限制可访问性。
此代码片段演示了如何更改 class 成员访问权限,来自 IBM。
struct A {
protected:
int y;
public:
int z;
};
struct B : private A { };
struct C : private A {
public:
using A::y;
using A::z;
};
struct D : private A {
protected:
using A::y;
using A::z;
};
struct E : D {
void f() {
y = 1;
z = 2;
}
};
struct F : A {
public:
using A::y;
private:
using A::z;
};
int main() {
B obj_B;
// obj_B.y = 3;
// obj_B.z = 4;
C obj_C;
obj_C.y = 5;
obj_C.z = 6;
D obj_D;
// obj_D.y = 7;
// obj_D.z = 8;
F obj_F;
obj_F.y = 9;
obj_F.z = 10;
}
根据文章,修改obj_F.z
是允许的,因为F
class中的using
声明没有生效,因此,F::z
仍然是 public
.
但是,当我将其插入 Compiler Explorer 时,它无法编译,说 F::z
是 private
。这是怎么回事?
这篇文章似乎有误。它说,
You cannot restrict the access to x with a using declaration.
但是我在标准中找不到这样的说法。 [namespace.udecl]/19
A synonym created by a using-declaration has the usual accessibility for a member-declaration.
[ Example:
class A { private: void f(char); public: void f(int); protected: void g(); }; class B : public A { using A::f; // error: A::f(char) is inaccessible public: using A::g; // B::g is a public synonym for A::g };
— end example ]
即使这个例子也在增加可访问性,但标准并没有说不能限制可访问性。