[英]Implementing a template class interface
我对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;
};
感谢您在解释我的逻辑失败的地方以及有关如何正确执行任务的任何提示方面的帮助。 谢谢!
1)运算符“ new”返回一个指针,而不是对象。
sorted<string>* sorted1 = new sorted<string>();
2)但是,在您的小示例中,无需使用“ new”创建sorted1。
sorted<string> sorted1;
忠告一词-Java不是C ++。 您犯了许多首次Java程序员在编写C ++代码时犯的两个错误,即1)认为创建对象必须使用“ new”,以及2)“ new”返回引用。
我注意到整个实现中存在以下其他异常情况:
class Sorted
不继承于所谓的sortedInterface
接口 class Sorted
定义构造函数的所有版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.