【问题标题】:What purpose do access specifiers for nested class serve?嵌套类的访问说明符有什么用途?
【发布时间】:2020-12-05 15:47:19
【问题描述】:

假设我有一个类 A 和一个私有嵌套类 B。据我了解,这意味着 B 不是公共 API 的一部分。这是否意味着公共和私有访问说明符只服务于程序员而不是用户?是否有可能意外地让用户访问私有嵌套类的公共数据成员?

【问题讨论】:

  • API 是一个应用程序编程接口,因此它旨在成为程序员的工具。不涉及任何安全方面。此外,一旦您的可执行文件/库提供给用户,其中的任何数据都可以被提取/反编译

标签: c++ access-specifier


【解决方案1】:

拥有一个私有的嵌套类并不意味着你不能不小心让它对“用户”可用:

#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

protectedprivate 会阻止您直接引用这些名称,但如果您有意(或无意)以不同的方式公开它们,那么此访问修饰符将无法保护您。

【讨论】:

  • 通知 auto b1 有效,但 A::B b1 无效,(因为名称是私有的)。
猜你喜欢
  • 1970-01-01
  • 2011-01-15
  • 2016-12-10
  • 2014-11-03
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多