【问题标题】:How to pass object by reference to a constructor如何通过引用将对象传递给构造函数
【发布时间】:2013-11-13 18:18:38
【问题描述】:

我想通过引用将对象传递给构造函数,但我遇到了问题,因为我不知道如何将它绑定到类的变量。

在这里我发布了一些我的代码并且错误出现了。

class ShortestPath{
    public:
        ShortestPath(Graph& graph): graph(graph){};[...]
    private:
        Graph *graph; 
};

在这种情况下,出现的错误是:

cannot convert `Graph' to `Graph*' in initialization 

如果我写了

ShortestPath(Graph& graph): *graph(graph){};[...]

错误是

expected identifier before '*' token 

当我调用构造函数时,我应该这样调用吗? 最短路径(图);

【问题讨论】:

    标签: c++ function object reference constructor


    【解决方案1】:

    由于您的 graph 是指向 Graph 的指针,您应该使用以下方式(作为另一个答案):

    ShortestPath(Graph& graph): graph(&graph) {};
                                      ^ // Get the pointer to object
    

     

    但是,如果您确定传递的graph 的生命周期大于并且等于ShortestPath 的对象的生命周期。您可以使用引用而不是指针:

    class ShortestPath{
        public:
            ShortestPath(Graph& graph): graph(graph){};
    
        private:
            Graph &graph; 
                  ^ // A reference to object
    };
    

    【讨论】:

    • 第二种方式有什么好处?
    • @giacomotb:如果可以的话,最好避免使用基于指针的解决方案,而不是使用非指针。引用不能引用 null。所以,我个人更喜欢使用引用方式,摆脱那些->的方式。
    【解决方案2】:

    您必须以这种方式更改您的代码:

    class ShortestPath{
    public:
        ShortestPath(Graph& graph): graph(graph){};[...]
    private:
        Graph &graph; 
    }
    

    或:

     class ShortestPath{
    public:
        ShortestPath(Graph& graph): graph(&graph){};[...]
    private:
        Graph *graph; 
    }
    

    【讨论】:

    • 您应该添加原因,因为它比如何更重要。
    • 当您使用 ShortestPath(Graph& graph): graph(graph) 您传递的是 Graph 而不是 Graph * (尽管它是对您的对象的引用而不是它的副本)。当你使用 :ShortestPath(Graph& graph): *graph(graph){} 它在语法上是错误的,因为你的指针在你的构造函数而不是对象之前。
    【解决方案3】:

    两种可能的解决方案:

    通过引用传递图形并存储指针

    // note that (&graph) gets the address of the graph
    ShortestPath(Graph& graph): graph(&graph) {};
    

    通过指针传递图形并存储指针

    ShortestPath(Graph* graph): graph(graph) {};
    

    【讨论】:

      【解决方案4】:

      你需要获取Graph对象的地址,像这样:

      class ShortestPath{
          public:
              ShortestPath(Graph& graph): graph(&graph){}
          private:
              Graph *graph; 
      };
      

      【讨论】:

      • 为什么不在私有成员变量中创建对对象的引用而不是指针?
      • @MelroyvandenBerg:这当然是可能的,并且根据用例,可能更可取。如果graph 可能为空,则可能是不可取的,例如有一个默认构造函数,没有任何东西可以初始化它。
      • 是的,但在大多数情况下在 C++ 中。对于普通类,我希望人们会使用引用,因为这确实避免了您使用空指针。也许在你的答案下面做一个小笔记?那Graph& graph;也很好。在这种情况下,评估将是:graph(graph)
      猜你喜欢
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 2014-09-08
      • 2016-02-15
      • 1970-01-01
      • 2014-06-04
      • 2010-11-17
      • 2013-07-05
      相关资源
      最近更新 更多