c++ - 如何通过对构造函数的引用传递对象

标签 c++ function object reference constructor

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

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

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 

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

最佳答案

你必须这样修改你的代码:

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

或:

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

关于c++ - 如何通过对构造函数的引用传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745551/

相关文章:

php - 格式化时差的函数

python - 将函数参数转换为列表时出现问题

javascript - 使用 jQuery 迭代创建更改函数

C++ 排序坐标存储为 vector 中的对象

c++ - 使用 strlen() 在堆栈中分配缓冲区

c++ - _Unwind_resume的Mingw多重定义

c++ - 奇怪的类声明

c++ - std::vector 使用 g++ 调试和发布构建

c++ - 关于C++常量语法的简单问题

javascript - 在对象定义中使用 undefined 作为值是一个好习惯吗?