簡體   English   中英

這一堆typedef應該是私有的還是公共的?

[英]Should this bunch of typedefs be private or public?

我正在寫一個代表圖形的類,所以我寫了下面的標題

class Graph {
public:
  Graph(); 
  Graph(int N);

  void addVertex();
  void addEdge(VertexNum v1, VertexNum v2, Weight w);


  std::pair<PathLength, Path> shortestPath
    (const VerticesGroup& V1, const VerticesGroup& V2);


private:
  typedef int                           VertexNum;
  typedef int                           Weight;
  typedef std::pair<VertexNum, Weight>  Edge;
  typedef std::vector<Edge>             Path;
  typedef size_t                        PathLength;
  typedef std::vector<VertexNum>        VerticesGroup;


  std::vector<std::list<Edge> > adjList;

  bool incorrectVertexNumber(VertexNum v);
};

我對上面的代碼有一些疑問:

  1. 我應該聲明一堆typedef是public還是private?
  2. 這是一種常規做法,當一個type將一個類型解析為不同的同義詞時(比如typedef int VertexNum; typedef int Weight;)?

在類的public接口中使用的任何typedef都應該在類的public部分中。 休息應該是private

1. C ++中的訪問控制純粹適用於名稱。 ISO / IEC 14882:2011 11 [class.access] / 4中有一個注釋和示例,表明這是意圖。

[...] [ Note: Because access control applies to names, if access control is applied to a typedef name, only the accessibility of the typedef name itself is considered. The accessibility of the entity referred to by the typedef is not considered. For example,

class A {
  class B { };
public:
  typedef B BB;
};

void f() {
   A::BB x; // OK, typedef name A::BB is public
  A::B y; // access error, A::B is private
}
—end note ]

2.沒關系,因為你可以使某些類型有意義且容易理解。

  1. 如果您聲明為private ,則無法在課堂外使用它們。 我想這不是你想要的,特別是如果typedef ed名稱在你的公共接口中顯示為參數類型。 如果限制在類中使用typedef ed名稱,則將其private
  2. 通常的做法是使用typedef將類型重命名為域級別的更可用/易於理解的名稱。

暫無
暫無

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

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