簡體   English   中英

實施模板類接口

[英]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”返回引用。

您的界面/實現有些​​問題。 類模板通常完全在聲明它的標頭中實現; 這是因為編譯器會為您與模板一起使用的每種類型創建一個全新的類型。

其次,在您的sortedInterface模板中,已將成員虛擬化,該成員仍需要一個定義,但不提供定義。 您可以將成員函數標記為= 0; 為了使它們全部都是純虛擬的 ,這意味着繼承您sortedInterface的類將必須實現這些成員。

第三,正如PaulMcKenzie指出的那樣, operator new()返回指向堆分配對象的指針,但是您期望使用值類型。

最后,如果您到處都在使用裸new() ,請看一下智能指針

我注意到整個實現中存在以下其他異常情況:

  • 接口應該是不可實例化的,但是在您的情況下可以實例化(因為甚至沒有單個純接口
    您所謂的界面中的虛擬函數)標准規則是
    將接口中的所有功能設為純虛擬(= 0)
  • class Sorted不繼承於所謂的sortedInterface接口
  • 您尚未在class Sorted定義構造函數的所有版本
  • 如果您希望多態性有效(Interface to Concrete),則
    需要在接口和接口中都具有虛擬類析構函數
    具體課

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM