【发布时间】:2014-02-02 22:03:59
【问题描述】:
我对 c++ 比较陌生,并且有一段时间让我的主程序实例化我的类。我习惯了 java,所以我不确定我是否在尝试这样做时混淆了这两种语言,这是我的问题,或者我只是没有正确理解这个概念。
我的程序的对象: 这个程序的对象是从一个接口创建一个模板类,该接口将生成一个排序数组,您可以在其中添加和删除项目,同时保持排序。
注意:请帮助我真正理解这个过程,只告诉我要使用的确切代码,因为我真的很想了解下一次我做错了什么.
第 1 步:我创建了排序界面:
sortedInterface.h
#ifndef _SORTED_INTERFACE
#define _SORTED_INTERFACE
#include <vector>
using namespace std;
template<class ListItemType>
class sortedInterface
{
public:
virtual bool sortedIsEmpty();
virtual int sortedGetLength();
virtual bool sortedInsert(ListItemType newItem);
virtual bool sortedRemove(ListItemType anItem);
virtual bool sortedRetrieve(int index, ListItemType dataItem);
virtual int locatePosition(ListItemType anItem);
}; // end SortedInterface
#endif
然后我使用接口创建了sorted.h文件:
sorted.h
#include "sortedInterface.h"
#include <iostream>
#ifndef SORTED_H
#define SORTED_H
using namespace std;
template<class ListItemType>
class sorted
{
public:
sorted();
sorted(int i);
bool sortedIsEmpty();
int sortedGetLength();
bool sortedInsert(ListItemType newItem);
bool sortedRemove(ListItemType anItem);
bool sortedRetrieve(int index, ListItemType dataItem);
int locatePosition(ListItemType anItem);
protected:
private:
const int DEFAULT_BAG_SIZE = 10;
ListItemType items[];
int itemCount;
int maxItems;
};
#endif // SORTED_H
最后我创建了 sorted.cpp(我现在只包含构造函数,因为我什至无法让它工作)
#include "sorted.h"
#include <iostream>
using namespace std;
template<class ListItemType>
sorted<ListItemType>::sorted()
{
itemCount = 0;
items[DEFAULT_BAG_SIZE];
maxItems = DEFAULT_BAG_SIZE;
}
我的主程序:
#include "sortedInterface.h"
#include "sorted.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
sorted<string> sorted1 = new sorted();
return 0;
};
感谢任何帮助解释我的逻辑在哪里失败以及如何正确执行我的任务的任何提示。谢谢!
【问题讨论】:
-
您遇到了什么错误?由于模板的工作方式,通常您还需要将模板定义放在头文件中。
-
使成员虚拟化仍然需要一个实现。 Pure virtual 可能是您所追求的。
-
关于术语,它是“类模板”,而不是“模板类”。 “类模板”不是类,它是制作类的模板。
标签: c++ class templates interface