c++ - 如何在这个例子中使用 `const` ness?

标签 c++ constructor constants

我有一些实现图形算法的代码;特别是,有这些片段会导致问题:

class Path{
private:
    const Graph* graph;

public:
    Path(Graph* graph_) : graph(graph_) {
        ...
    }

(应该创建 Path 对象,该对象带有指向 图)

class GradientDescent{
private:
    const Graph graph;
public:
    Path currentPath;
    GradientDescent(const Graph& graph_) : graph(graph_), currentPath(Path(&graph_)) {}

(应该创建一个 GradientDescent 对象,它有一个 const Graph 和一个非常量 Path)

问题是,因为我只是想弄清楚如何使用 const,我得到了这个错误:

error: no matching constructor for initialization of 'Path'
    GradientDescent(const Graph& graph_) : graph(graph_), currentPath(Path(&graph_)) {}

longest_path.cpp:103:9: note: candidate constructor not viable: 1st argument ('const Graph *') would lose const qualifier
    Path(Graph* graph_) : graph(graph_) {

最佳答案

问题是您的Path 的构造函数需要一个指向非const Graph 的指针。

要摆脱这个问题,只需更改您的构造函数声明:

Path(const Graph* graph_) : graph(graph_) {
    ...
}

关于c++ - 如何在这个例子中使用 `const` ness?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985160/

相关文章:

C++链表在删除具有重复值的节点时会出现段错误

c++ - 将具有相同键的节点添加到属性树

c++ - 使用 Auto 时在派生类中使用虚拟析构函数强制复制构造函数

Javascript 'THIS' 值使用构造函数而不分配给变量

c++ - 如何在 C++ 中指定 unsigned char 类型的整数文字?

c++ - 类中的 const 成员出错

c++ - 为什么静态数组成员变量在调用对象的实例后不显示任何内容?

c++ - DLL对执行速度的影响

c++ - 如何使用 _WIN32 和 _CYGWIN_ 宏

c++ - 显式默认构造函数做什么?