【问题标题】:C++, instantiating a generic Node storing an instance of an object using templatesC ++,使用模板实例化存储对象实例的通用节点
【发布时间】:2016-04-11 02:12:57
【问题描述】:

我目前正在尝试为数据结构类实现双向链表。

我目前已经实现了一个通用的 Node* 类,并且想要保存我已经实现的另一个类 Student(int i, int j) 的实例。

这是我试图在我的主要方法中做的事情:

Student student1 = Student(10,11);
Node<Student()> node1 = Node<Student()> (student1);

这是我收到的错误。 当 Node 保存像 int 这样的原始数据类型时,一切都工作得很好,但我不确定如何解释存储 int 和存储 Student 对象之间的区别。

我希望有任何见解或朝着正确的方向前进。 谢谢。

这是我的 Node 实现。

#ifndef NODE_H
#define NODE_H

template <class T>
class Node
{
    public:
    Node();
    Node(T k);
    virtual~Node();

    T key;
    Node<T>* prev;
    Node<T>* next;
};
#endif

//default constructor
template <class T>
Node<T>::Node()
{
    prev = NULL;
    next = NULL;
}

 template <class T>
Node<T>::Node(T k)
{
    prev = NULL;
    next = NULL;
    key = k;
}

template<class T>
Node<T>::~Node()
{
//implement 
}

学生.cpp

#include "Student.h"

Student::Student()
{
    mArrivalTime = 0;
    mTimeNeeded = 0;
}
Student::Student(int arrivalTime, int timeNeeded)
{
    mArrivalTime = arrivalTime;
    mTimeNeeded = timeNeeded;
}

Student::~Student()
{
     //implement
}

int Student::getArrivalTime()
{
    return mArrivalTime;
}

int Student::getTimeNeeded()
{
    return mTimeNeeded;
}

学生.h

#ifndef STUDENT_H
#define STUDENT_H

using namespace std;
class Student
{
    private:
        int mArrivalTime;
        int mTimeNeeded;

     public:
        Student();
        Student(int arrivalTime, int timeNeeded);
        ~Student();
        int getArrivalTime();
        int getTimeNeeded();
};
#endif

【问题讨论】:

    标签: c++ templates object generics nodes


    【解决方案1】:

    不要用(),只用类名。例如:

    Node<Student> node1 = Node<Student> (student1);
    

    【讨论】:

    • 我很好奇这是否可行,但是当我这样做时,我收到此错误:架构 x86_64 的未定义符号:“Student::Student(int, int)”,引用自:_main in Assignment4-1de395.o “Student::Student()”,引用自:Assignment4-1de395.o “Student::~Student()”中的 Node::Node(Student),引用自:Assignment4-中的 _main 1de395.o Node::~Node() in Assignment4-1de395.o ld:未找到架构 x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
    • 这是一个链接器错误,这可能意味着编译步骤有效。我猜您需要将 Student.cpp 添加到您的 g++ 命令行,因此它与您的主 .cpp 文件链接。
    • 啊,当然。我已经习惯了为这个作业使用模板,而不必编译我完全忘记了需要编译的 Student.cpp 的头文件。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多