2016-10-11 5 views
1

그래프 알고리즘을 구현하는 몇 가지 코드가 있습니다. 특히 문제를 일으킬 이러한 단편이있다 :이 예제에서`const`ness를 사용하는 방법은 무엇입니까?

(a 그래프 상수 포인터 Path 객체를 생성하도록되어)
class Path{ 
private: 
    const Graph* graph; 

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

을 작성하도록되어

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

(CONST Graph와 const가 아닌 Path)가 GradientDescent 객체

난 그냥 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_) { 
+3

'경로 (const를 그래프 * graph_)' – krzaq

+0

당신은'CONST 및'에서 주소를 복용 그것은'const를해야하므로 * '. – Galik

+1

@krzaq 내가 놓친 걸 믿을 수 없다 ... 대답으로 게시하면 받아 들일 것이다. – Akiiino

답변

1

문제는 당신 Path의 생성자는 포인터가 constGraph을 비 - 기대한다는 것입니다 :이 오류가 발생합니다.

단순히 생성자 선언 변경이 문제를 제거하려면 :

Path(const Graph* graph_) : graph(graph_) { 
    ... 
} 
관련 문제