我是 C++ 的新手,我花了很多时间让我的主程序实例化我的类。我习惯了 java,所以我不确定我在尝试这样做时是否混淆了两种语言,这是我的问题,或者我可能只是没有正确理解这个概念。
我的程序的目标:这个程序的目标是从一个接口(interface)创建一个模板类,该接口(interface)将生成一个排序数组,您可以在保持排序的同时添加和删除项目。
注意:请帮助我真正理解这个过程,只是告诉我要使用的确切代码,因为我真的很想知道我下次做错了什么.
第 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
然后我使用接口(interface)创建了 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) operator "new"返回一个指针,而不是一个对象。
sorted<string>* sorted1 = new sorted<string>();
2) 但是,在您的小示例中,无需使用“new”创建 sorted1。
sorted<string> sorted1;
忠告——Java 不是 C++。您犯了很多新手 Java 程序员在编写 C++ 代码时犯的两个错误,即 1) 认为要创建一个对象,您必须使用“new”,以及 2),“new”返回一个引用。
关于c++ - 实现模板类接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516863/