如何将对象通过引用传递给构造函数

5

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

这里我发布一些我的代码片段和出现的错误。

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 

当我调用构造函数时,我应该像这样调用吗?ShortestPath(Graph);

4个回答

12

您必须按照以下方式更改您的代码:

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

3
你应该加上为什么,因为这比如何更重要。 - jnovacho
当您使用ShortestPath(Graph& graph):graph(graph)时,您传递的是Graph而不是Graph (尽管它是对您的对象的引用而不是副本)。而当您使用:ShortestPath(Graph& graph):graph(graph){}时,语法上是错误的,因为您的指针在构造函数之前而不是对象。 - abdolah

3

两种可能的解决方案:

将图形作为引用传递并存储指针

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

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

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

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
1
@giacomotb:如果可以的话,最好避免使用指针基础解决方案而不是非指针。引用不能引用空值。因此,我个人更喜欢使用引用方式并摆脱那些 -> 方式。 - masoud

0
您需要获取图形对象的地址,就像这样:

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

为什么不在私有成员变量中创建一个对象的引用,而不是指针? - Melroy van den Berg
@MelroyvandenBerg:这当然是可能的,根据使用情况而定,可能更可取。如果graph可能为空,例如具有没有要初始化它的默认构造函数,则可能不希望这样做。 - Fred Larson
1
在C++中大多数情况下是正确的。对于普通类,我希望人们使用引用,因为这可以避免使用空指针。也许在你的答案下面加一个小注释?那么Graph& graph也是可以的。在这种情况下,评估将是:graph(graph) - Melroy van den Berg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接