2016-10-07 1 views
0

私は、文字通り、以下に怖がらています:C++ダブルポインタ知られていない変換

template <class T> // int, float, double etc.. 
class Graph { 
public: 

    // Documentation, it has to be between [0..100] 
    Graph(int size = 10, int density = 10, T range = 0): 
    m_size(size), 
    m_density(density), 
    m_range(range) { 
    generate(); 
    } 

    ~Graph() { 
    for (int i = 0; i < m_size; i++) 
    delete[] m_graph[i]; 
     delete[] m_graph; 
    } 

    [..] 

    static Graph<T>* custom(T** cgraph, int size, T range) { 
    Graph<T> *graph = new Graph<T>(size, 10, range); 
    for (int i = 0; i < size; i++) 
     delete[] graph->m_graph[i]; 
    delete[] graph->m_graph; 
    graph->m_graph = cgraph; 
    } 


private: 
    T** m_graph; 
    [ .. ] 
}; 

int nodes[4][4] = { 
    { 6, 5, 2, 5 }, 
    { 5, 6, 3, 3 }, 
    { 1, 3, 6, 1 }, 
    { 5, 3, 1, 6 } 
}; 

int main() { 
    Graph<int> *graph = Graph<int>::custom(nodes, 4, 5); 
} 

それが悪い、次のエラーを報告し、コンパイルに失敗して何?

g++ graph.cpp -o test_graph 
graph.cpp: In function ‘int main()’: 
graph.cpp:191:55: error: no matching function for call to ‘Graph<int>::custom(int [4][4], int, int)’ 
    Graph<int> *graph = Graph<int>::custom(nodes, 4, 5); 
                ^
graph.cpp:60:20: note: candidate: static Graph<T>* Graph<T>::custom(T**, int, T) [with T = int] 
    static Graph<T>* custom(T** cgraph, int size, T range) { 
        ^
graph.cpp:60:20: note: no known conversion for argument 1 from ‘int [4][4]’ to ‘int**’ 

それは間違っていますね。

+0

あなたは 'nodes'をそのアドレスで渡すべきではありません。 'nodes'は' int ** 'ですが、'&nodes'は 'int ***'です。 –

+1

配列とポインタの違いについて知る必要があります。 'nodes'はintの配列の配列です。 intへのポインタの配列ではありません。 –

+0

@MohamedMoanis: 'nodes'は絶対にありません。*' int ** 'ではありません。 '(int [4])*'に崩壊します。 –

答えて

1

nodesをintへのポインタの配列で作る必要があります。

int nodes_v[4][4] = { 
    { 6, 5, 2, 5 }, 
    { 5, 6, 3, 3 }, 
    { 1, 3, 6, 1 }, 
    { 5, 3, 1, 6 } 
}; 

int *nodes[4] = { nodes_v[0], nodes_v[1], nodes_v[2], nodes_v[3] }; 

また、それがカスタムグラフであり、設定されている場合、デストラクタはメモリを削除するべきではないとマークするグラフ変数に追加メンバーを追加する必要があります。

フラグにcustomフラグを渡し、設定されている場合はメモリを割り当てることを邪魔しないプライベートコンストラクタを与えることをお勧めします。

Graph(int size, int density, T range, bool custom): 
    m_size(size), 
    m_density(density), 
    m_range(range), 
    m_custom { 
    } 

    Graph(int size = 10, int density = 10, T range = 0): 
    Graph(size, density, range, false) { 
    generate(); 
    } 

    static Graph<T>* custom(T** cgraph, int size, T range) { 
     Graph<T> *graph = new Graph<T>(size, 10, range, true); 
     graph->m_graph = cgraph; 
    } 

最後に、コピーコンストラクタと代入演算子を処理する必要があります(削除するだけです)。

関連する問題