【问题标题】:A node class for Graphs (c++)Graphs 的节点类 (c++)
【发布时间】:2015-11-04 10:47:18
【问题描述】:

我正在尝试为节点构建一个类。但是,似乎像我在下面那样使用复制构造会产生错误:error: conversion from 'Node<int>*' to non-scalar type 'Node<int>' requested

编译器指向Node<int> child= new Node<int>(*(n.returnChildren()[0]));这一行

请注意我的问题的目的是学习 C++,我知道我可以在网上找到更好的课程。谢谢你

这是我的代码:

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <iterator>

using namespace std;

/* ******************************************************* Node ********************************************************* */

template<class T>
class Node
{
    private:
        T _value;
        vector<Node*> children;

    public:
        Node(T value);
        Node(const Node<T>& node);
        void AddChild(Node<T>* node);
        T getValue() const;
        vector<Node<T>*> returnChildren() const;
        //~Node();
};

template <class T>
Node<T>::Node(T value):_value(value)
{
    children.push_back(NULL);
}

template <class T>
Node<T>::Node(const Node& node):_value(node.getValue()), 
                                children(node.returnChildren())
{
}

template <class T>
void Node<T>::AddChild(Node* node)
{
    if (children[0]=NULL){children.pop_back();};
    children.push_back(node);
}

template <class T>
T Node<T>::getValue() const
{
    return _value;
}

template <class T>
vector<Node<T>*> Node<T>::returnChildren() const
{
    return children;
}
/*
template <class T>
Node<T>::~Node()
{
    for (vector<Node<T>*>::iterator it=children.begin() ; it!=children.end() ; it++)
    {
                    delete (*it);
    }
}*/



int main()
{
    Node<int> n(3);
    Node<int> nn(4);
    n.AddChild(&nn);
    Node<int> child= new Node<int>(*(n.returnChildren()[0]));
}

【问题讨论】:

  • 我可能会帮助标记发生编译器错误的位置。
  • vector 孩子;我想你实际上可以为 Node 指针定义类模板如下:vector*> children;

标签: c++ compiler-errors nodes


【解决方案1】:

错误消息中的所有内容都已说明。 new 返回一个指向新创建对象的指针,而不是对象本身。 请改用以下行:

Node<int> *child = new Node<int>(*(n.returnChildren()[0]));

使用后别忘了delete child;

更新: 你不需要push_back(NULL)。您最好将向量留空并删除AddChild 中的检查。

更新 2: 顺便说一句,这不是比较,而是一个赋值:

if (children[0]=NULL){;;;};

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2016-02-16
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多