【问题标题】:How to use `const`ness in this example?在这个例子中如何使用`const`ness?
【发布时间】:2016-10-11 19:27:58
【问题描述】:

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

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 对象,该对象具有一个常量Graph 和一个非常量Path

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

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* graph_)
  • 您从const& 获取地址,所以它必须是const*
  • @krzaq 我不敢相信我错过了...如果您将其发布为答案,我会接受它

标签: c++ constructor constants


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多