代码之家  ›  专栏  ›  技术社区  ›  kesarling

为什么在ctor中不允许访问成员对象的成员?

  •  1
  • kesarling  · 技术社区  · 5 年前

    类边缘:

    class Edge {
        int dist = 0;
        std::pair<Node, Node> ends;
    public:
        Edge() = default;
        explicit Edge(const int idist) : dist(idist) { }
        explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist) {
            ends.first = end1;
            ends.second = end2;
        }
        ~Edge() = default;
    };
    

    explicit Edge(const int idist, Node& end1, Node& end2) ,为什么不允许我使用语法?:

    explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist), ends.first(end1), ends.second(end2) { }
    
    2 回复  |  直到 5 年前
        1
  •  5
  •   songyuanyao    5 年前

    这是不允许的。作为的语法 member initializer list ,

    class-or-identifier ( expression-list(optional) ) (1) 
    class-or-identifier brace-init-list   (2) (since C++11)
    

    同时 ends.first ends.second ends 总的来说,例如。

    explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist), ends(end1, end2) { }
    
        2
  •  2
  •   Lytigas    5 年前

    你想做的事是允许的,但你的方式是不允许的。

    初始值设定项列表指定如何将包含未初始化字节的随机内存位转换为有效对象。然后构造函数可以处理这个新对象,但对象状态需要预先初始化。对于默认初始化导致的未初始化值,有一些警告,但是在初始化器列表中唯一有效的操作是调用成员的构造函数。( See here

    就你而言, first second 是一个 pair

    解决方案是使用其构造函数之一一次性初始化整个对:

    explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist), ends(end1, end2) { }