从类指针到int的无效转换

Kra*_*ken 0 c++ memory-management new-operator

我无法确定下面的代码出了什么问题

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;
}
Run Code Online (Sandbox Code Playgroud)

我懂了

从Node *到int的无效转换

Fra*_*eux 5

new返回一个指针。您无法分配指向的指针n,而是一个Node。快速解决方案是将有问题的行更改为Node * n = new Node(10,10);auto n = new Node(10,10);

但是使用new不再是现代下的动态创建对象++推荐的解决方案。身高auto n = std::make_unique<Node>(10, 10);不是这使得n一个智能指针。通过使用智能指针,您不必手动跟踪所有权,也不必只记住delete一次对象。如果发生意外异常,还可以使代码更健壮。您需要#include <memory>。请参阅std::make_uniquestd::make_shared

#include <memory>

int main()
{
    auto n = std::make_unique<Node>(10,10);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

尽管在这种情况下,似乎不需要动态分配。只需使用Node n{10, 10};就足够了。