【问题标题】:C++ double pointer not known conversionC++ 双指针未知转换
【发布时间】:2016-10-07 10:05:57
【问题描述】:

我真的被以下内容吓坏了:

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**’

我觉得很对,怎么了?

【问题讨论】:

  • 你应该传递nodes而不是它的地址。 nodes 是 int** 而 &amp;nodes 是 int***,不考虑 const 的东西。
  • 你需要了解一下数组和指针的区别。 nodes 是一个整数数组。它不是指向 int 的指针数组。
  • @MohamedMoanis: nodes 绝对是不是 int **。它衰减到(int [4])*
  • 演员可以成功(int**) nodes。
  • 另外,当您在custom 返回的CGraph 上调用delete 时,它会尝试删除传入的数组——这是行不通的。

标签: c++ templates pointers


【解决方案1】:

您需要通过指向 int 的指针数组来生成 nodes。

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] };

你还需要给Graph变量添加一个额外的成员来标记它是一个自定义图,如果设置了,析构函数不应该删除内存。

最好为 Graph 提供一个私有构造函数,该构造函数传入 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;
  }

最后,您需要处理复制构造函数和赋值运算符(从删除它们开始)。

【讨论】:

    猜你喜欢
    • 2021-01-08
    • 2020-12-10
    • 1970-01-01
    • 2013-02-20
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多