从 class 指针到 int 的无效转换
Invalid conversion from class pointer to int
我无法弄清楚下面代码中的问题所在
class Node
{
private:
int index, value;
public:
Node(int index=0, int value=0):index(index),value(value){}
int getIndex()
{
return index;
}
int getValue()
{
return value;
}
};
int main()
{
Node n = new Node(10,10);
return 0;
}
我明白了
invalid conversion from Node* to int
使用新参数时需要使用指针。行
Node n = new Node(10,10);
应该是
Node* n = new Node(10,10);
错误消息是因为从 new 返回的值是内存中的一个数字位置,而编译器知道表示它的最接近的数据类型是 int。
如果你想把它放在堆栈上
Node n(10, 10);
对象将在堆栈上创建。它在函数结束时超出范围,甚至在它之前(例如,如果它是在循环中声明的)。
如果你想在堆上
Node *n = new Node(10, 10);
对象分配在堆上,指向它的指针在栈上。它的表现比 Java 的 "references" 更符合您的预期。当指针超出范围时,对象不会被删除。相反,delete
必须在某个时候被调用,否则内存将被泄漏(不像 Java 的 "references",它们被垃圾收集)。
new
returns 一个指针。您不能将指针分配给 n
,它是 Node
。快速解决方法是将有问题的行更改为 Node * n = new Node(10,10);
或 auto n = new Node(10,10);
.
然而使用new
不再是现代c++中动态创建对象的推荐解决方案。更喜欢 auto n = std::make_unique<Node>(10, 10);
而不是 n
a smart pointer. By using smart pointers, you relieve yourself from having to manually track ownership and from having to remember to delete
your object exactly once. You also make your code much more robust in case of unexpected exceptions. You'll need to #include <memory>
. See std::make_unique
and std::make_shared
:
#include <memory>
int main()
{
auto n = std::make_unique<Node>(10,10);
return 0;
}
虽然在这种情况下,似乎不需要动态分配。只需使用 Node n{10, 10};
就足够了。
我无法弄清楚下面代码中的问题所在
class Node
{
private:
int index, value;
public:
Node(int index=0, int value=0):index(index),value(value){}
int getIndex()
{
return index;
}
int getValue()
{
return value;
}
};
int main()
{
Node n = new Node(10,10);
return 0;
}
我明白了
invalid conversion from Node* to int
使用新参数时需要使用指针。行
Node n = new Node(10,10);
应该是
Node* n = new Node(10,10);
错误消息是因为从 new 返回的值是内存中的一个数字位置,而编译器知道表示它的最接近的数据类型是 int。
如果你想把它放在堆栈上
Node n(10, 10);
对象将在堆栈上创建。它在函数结束时超出范围,甚至在它之前(例如,如果它是在循环中声明的)。
如果你想在堆上
Node *n = new Node(10, 10);
对象分配在堆上,指向它的指针在栈上。它的表现比 Java 的 "references" 更符合您的预期。当指针超出范围时,对象不会被删除。相反,delete
必须在某个时候被调用,否则内存将被泄漏(不像 Java 的 "references",它们被垃圾收集)。
new
returns 一个指针。您不能将指针分配给 n
,它是 Node
。快速解决方法是将有问题的行更改为 Node * n = new Node(10,10);
或 auto n = new Node(10,10);
.
然而使用new
不再是现代c++中动态创建对象的推荐解决方案。更喜欢 auto n = std::make_unique<Node>(10, 10);
而不是 n
a smart pointer. By using smart pointers, you relieve yourself from having to manually track ownership and from having to remember to delete
your object exactly once. You also make your code much more robust in case of unexpected exceptions. You'll need to #include <memory>
. See std::make_unique
and std::make_shared
:
#include <memory>
int main()
{
auto n = std::make_unique<Node>(10,10);
return 0;
}
虽然在这种情况下,似乎不需要动态分配。只需使用 Node n{10, 10};
就足够了。