问题描述
假设我有一个带有私有嵌套类B的类A。据我了解,这意味着B不属于公共API。这是否意味着公共和私有访问说明符仅服务于程序员而不是用户?有什么方法可以使用户意外访问私有嵌套类的公共数据成员吗?
解决方法
拥有私有的嵌套类并不意味着您不能不小心将其提供给“用户”:
#include <iostream>
#include <type_traits>
class A {
private:
class B {
public:
int x = 2;
};
public:
B getB() { return B(); }
};
int main() {
A a;
// a returns B so you have access to the public member x
auto b1 = a.getB();
std::cout << b1.x << std::endl;
// or get the return type to create an instance of B
using B = std::result_of_t<decltype(&A::getB)(A)>;
B b2;
std::cout << b2.x << std::endl;
}
因此,如果您在A
中有一个函数public
,并且可以公开B
(或其他任何可以公开B
的函数,并且“用户”),则即使该嵌套类为private
,用户也可以引用该嵌套类。
protected
和private
阻止您直接引用名称,但是如果您有意(或无意间)以不同的方式公开名称,则此访问修饰符将不会为您提供保护。