簡體   English   中英

使用模板和新/刪除運算符(C ++)編譯錯誤

[英]Compile errors with templates and new/delete operators (C++)

我試圖建立一個矢量風格的類,並且為了使用模板以及newdelete運算符,我有以下這段代碼:

template <class type2> class storage
{
         private:
                 type2 *organs;
         public:
                int num;
                storage(); //constructor
                ~storage(); //destructor
                void operator+(type2 newone);
                void operator-(int howmany);
                type2 operator[](int place);
};


storage<class type2>:: ~storage()
{
          delete[] organs; //~~~~~~~Error number 1~~~~~~~~~~
}

void storage<class type2>:: operator+(type2 newone)
{ //                        ~~~~~~~~~~~Error number 2~~~~~~~~~~~~~~
     organs = new type2[1];
     num++;
     oragns[num-1] = newone;
}

編譯器(Dev C ++)在錯誤1上寫入此錯誤:

無效使用未定義類型`struct type2'

而此錯誤出現在錯誤編號2:

`newone'具有不完整的類型

但是,我不明白怎么了。 有什么提示嗎?

您需要指定用於這些方法的模板,或將函數實現移至類中。

template <class type2>
storage<class type2>:: ~storage()
{
      delete[] organs;
}

可能是最簡單的解決方案。 同樣的方法也可以解決第二個錯誤。

編輯:

找到了一個不錯的模板教程,其中涵蓋了其他內容。

http://www.cplusplus.com/doc/tutorial/templates/

除了編譯錯誤外,此代碼中還有一些主要錯誤。

  • Operator +的簽名完全錯誤。 您可能會使用operator + =作為附加,大概就是您在做什么。 您可能應該返回對self的引用。
  • 操作員-也許也使操作員-=
  • 如果應該添加operator +,則不這樣做。 您只是在分配一個新元素,丟失了以前無法恢復的任何內容,即該內存沒有指向該元素的指針,因此無法刪除它。
  • 定義了析構函數后,您需要處理復制和分配
  • 理想情況下,operator []將具有2個重載,一個const和一個非const。 如果您確實想按值返回,則應將其設為const。

暫無
暫無

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

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