开发者

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

开发者 https://www.devze.com 2023-02-05 12:58 出处:网络
I\'m trying to build a vector-style class and in order to use templates as well as the new, delete operators I have this piece of code:

I'm trying to build a vector-style class and in order to use templates as well as the new, delete operators I have this piece of code:

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;
}

The compiler (Dev C++) writes this error on Error number 1:

invalid use of undefined type `struct type2'

And this error on Error Number 2:

`newone' has incomplete type

However, I don't understand what's wrong. Any hints?


You need to specify what template you are using for those methods or move the function implementation into the class.

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

Probably the easiest solution. The same should work for your second error as well.

EDIT:

Found a nice template tutorial which covers this, among other things.

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


There are major bugs in this code aside from the compilation error.

  • Totally wrong signature for operator+. You might use operator+= as an append, which presumably is what you are doing. You should probably return a reference to self.
  • operator- also perhaps make operator-=
  • If operator+ is supposed to append you are not doing so. You are just allocating a new element, losing whatever you had before with no way of recovering it, i.e. that memory has no pointers pointing to it and you cannot delete it.
  • As you have a destructor defined you need to handle copying and assignment
  • operator[] would ideally have 2 overloads, one const and one non-const. If you do really want to return by value you should probably make it const.
0

精彩评论

暂无评论...
验证码 换一张
取 消