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
最佳答案
new返回一个指针。您不能将指针分配给 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一个smart pointer .通过使用智能指针,您不必手动跟踪所有权,也不必记住 delete。你的对象恰好一次。您还可以使您的代码在出现意外异常时更加健壮。你需要 #include <memory> .参见 std::make_unique和 std::make_shared :
#include <memory>
int main()
{
auto n = std::make_unique<Node>(10,10);
return 0;
}