Ok so i have a class Vector:
#include <cstdlib>
class Vec
{
private:
size_t size;
int * ptab;
public:
Vec(size_t n);
~Vec() {delete [] ptab;}
size_t size() const {return size;}
int & operator[](int n) {return ptab[n];}
int operator[](int n) const {return ptab[n];}
void operator=(Vec const& v);
};
inline Vec::Vec(size_t n) : size(n), ptab(new int[n])
{ }
and the problem is that in one of my homework exercises i have to extend constructor def, so all elements will be initialized with zeros. I thought i know the basics but cant开发者_如何转开发 get through this dynamic array -.-
ps. sry for gramma and other mistakes ;)
In a new-expression you can use a pair of parentheses as an initializer to value-initialize (which for an array of int
zero-initializes every element) an object.
new int[n]()
Other points:
As your user-defined destructor deallocates a dynamically allocated array you need a user-defined copy constructor to ensure that your class is easy to use safely.
Your copy assignment operator should have a return type of
Vec&
, notvoid
and return*this
to conform with common conventions and to work with standard container templates.You should consider declaring the single parameter constructor
explicit
unless you really want to enable implicit conversions fromsize_t
toVec
.
精彩评论