【问题标题】:Should this bunch of typedefs be private or public?这一堆 typedef 应该是私有的还是公共的?
【发布时间】:2014-05-23 08:17:42
【问题描述】:

我正在写一个代表图表的类,所以我写了以下标题

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. 当一个 typedef 将一种类型定义为不同的同义词(如 typedef int VertexNum; typedef int Weight;)时,这是一种正常的做法吗?

【问题讨论】:

    标签: c++ class graph typedef


    【解决方案1】:

    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。 没关系,因为您可以使某些类型有意义且易于理解。

    【讨论】:

      【解决方案2】:

      在类的public 接口中使用的任何typedef 都应该在类的public 部分中。休息应该是private

      【讨论】:

        【解决方案3】:
        1. 如果您声明为private,您将无法在课堂外使用它们。我想这不是您想要的,特别是如果 typedefed 名称作为参数类型出现在您的公共界面中。如果您限制在班级中使用 typedefed 名称,则将其设为 private
        2. 在域级别将使用 typedef 的类型重命名为更实用/更易于理解的名称当然是常见的做法。

        【讨论】:

          猜你喜欢
          • 2011-09-12
          • 2012-03-14
          • 1970-01-01
          • 1970-01-01
          • 2016-03-27
          • 2013-01-02
          • 1970-01-01
          • 2022-12-07
          • 1970-01-01
          相关资源
          最近更新 更多