c++双指针不知道转换
C++ double pointer not known conversion
我真的被下面这些吓坏了:
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**’
看起来很好,怎么了
您需要通过指向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;
}
最后,需要处理复制构造函数和赋值操作符(从删除它们开始)。
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 叮当不知道PTRDIFF_MAX?
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- 不知道某个东西是否被忽略会引入未定义的行为吗
- Visual C++(VS2017)中用户定义的转换不明确
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 我不知道这条线是做什么的
- C++通常的算术转换不转换
- 字符类型转换不兼容
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- 基类到派生模板类的强制转换指针,而不知道类型
- 从没有强制转换的整数中获取指针。知道什么,但不知道如何
- c++双指针不知道转换
- 转换为ctype,但我不知道这些函数在做什么
- 不知道参数 1 从 sf::Vector2i 到 const sf::Vector2i& 的转换<float>
- Numpy NDPointer:不知道如何转换参数 1
- 将 void* 强制转换为模板化类型时不知道模板参数类型