开发者

Constructor Definition

开发者 https://www.devze.com 2023-02-02 04:23 出处:网络
Ok so i have a class Vector: #include <cstdlib> class Vec { private: size_t size; int * ptab; public: Vec(size_t n);

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&, not void 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 from size_t to Vec.

0

精彩评论

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