C++ noob here。我試圖通過實施 鏈接列表類作爲其數據結構來創建學生信息程序。templateClassName <className> t;無法將類分配給模板類參數
LinkedList.h
#pragma once
#include <stdexcept>
template <typename T>
class LinkedList
{
private:
struct Node
{
T elem;
Node *prev;
Node *next;
};
Node *header;
Node *trailer;
int size;
public:
LinkedList()
{
header = new Node;
trailer = new Node;
header->next = trailer;
trailer->prev = header;
}
~LinkedList()
{
while (!isEmpty())
removeFirst();
delete header;
delete trailer;
}
const int& n_elem() const
{
return size;
}
const bool isEmpty() const
{
return size == 0;
}
const T& getFirst() const
{
if (isEmpty())
throw std::out_of_range("List is empty.");
return header->next->elem;
}
const T& getLast() const
{
if (isEmpty())
throw std::out_of_range("List is empty.");
return trailer->prev->elem;
}
void addFirst(const T& item)
{
addBetween(item, header, header->next);
}
void addLast(const T& item)
{
addBetween(item, trailer->prev, trailer);
}
void addAt(int index, const T& item)
{
Node *node = header;
for (int i = 0; i < index; i++)
node = node->next;
addBetween(item, node, node->next);
}
const T removeFirst()
{
if (isEmpty())
throw std::out_of_range("List is empty.");
return remove(header->next);
}
const T removeLast()
{
if (isEmpty())
throw std::out_of_range("List is empty.");
return remove(trailer->prev);
}
const T removeAt(int index)
{
if (isEmpty())
throw std::out_of_range("List is empty.");
Node *node = header;
for (int i = 0; i < index; i++)
node = node->next;
return remove(node->next);
}
const T& itemAt(int index) const
{
if (isEmpty())
throw std::out_of_range("List is empty.");
Node *node = header;
for (int i = 0; i < index; i++)
node = node->next;
return node->next->elem;
}
protected:
void addBetween(const T& item, Node *predecessor, Node *successor)
{
Node *newest = new Node;
newest->prev = predecessor;
newest->next = successor;
predecessor->next = newest;
successor->prev = newest;
size++;
}
const T remove(Node *node)
{
Node *predecessor = node->prev;
Node *successor = node->next;
predecessor->next = successor;
successor->prev = predecessor;
T oldItem = node->elem;
size--;
delete node;
return oldItem;
}
};
Student類定義如下。
Program.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include "LinkedList.h"
using namespace std;
class Student
{
public:
string name;
string id;
int score;
static const int total = 100;
double grade;
Student(string n, string i, int s)
{
name = n;
id = i;
score = s;
grade = getGrade(score);
}
private:
double getGrade(int score)
{
return (23.0/3.0 - ((20.0 * score)/(3.0 * total)));
}
};
LinkedList<Student> l;
int main()
{
//Some code here
return 0;
}
我不知道原因
LinkedList<Student> l;
產生一個錯誤:
LinkedList<Student>::Node::Node(void)': attempting to reference a deleted function
但是當我使用:
LinkedList<Student*> l;
沒有錯誤。
請幫忙。 我正在使用Visual Studio 2015.
對不起,對英語不好。
試試你的鏈接列表導入前移動類定義或把類一個.cpp和.h文件。 – ajputnam