[英]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.