簡體   English   中英

嵌套 class 的訪問說明符有什么用途?

[英]What purpose do access specifiers for nested class serve?

假設我有一個 class A 和一個私有嵌套 class B。據我了解,這意味着 B 不是公共 API 的一部分。 這是否意味着公共和私有訪問說明符只服務於程序員而不是用戶? 是否有可能意外讓用戶訪問私有嵌套 class 的公共數據成員?

擁有私有嵌套 class 並不意味着您不能意外地將其提供給“用戶”:

#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中有一個 function 是public的,並且公開了B (或任何其他能夠公開B並且“用戶”可以訪問的 function ),那么用戶將能夠引用嵌套的 ZCBBADBC21 甚至如果它是private的。

protectedprivate阻止您直接引用名稱,但如果您故意(或意外)以不同的方式公開它們,則此訪問修飾符不會保護您免受此影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM