Array as primitive data members in c plus plus program?
C-style arrays can be used as data members, both as fixed-size
arrays or as dynamic arrays. The following examples demonstrate how
they could be used as one-dimensional data members.
class a {
private:
int b[10] {0}; // in-class initialisation (all elements
zero).
public:
int& operator[] (unsigned index) {
if (index>=10) throw std::range_error();
return b[index]; }
};
class c {
public:
c (unsigned sz=10): size(sz), p (size?new int[size]:nullptr)
{
memset (p, 0, size); }
c (const s& _s): size(_s.size), p (size?new
int[size]:nullptr) {
if (size) memcpy (p, _s.p, size); }
c (s&& _s): size(_s.size), p (_s.p) { _s.p=nullptr; } //
swap resources
c& operator= (const s& _s) {
if (p) delete [] p;
size = _s.size;
p = (size?new int[size]:nullptr);
if (size) memcpy (p, _s.p, size); }
c& operator= (s&& _s) {
size = _s.size;
p = _s.p;
_s.p=nullptr; } // swap resources
~c() { if (p) delete [] p; }
int& operator[] (unsigned index) {
if (index>=size) throw std::range_error();
return p[index]; }
private:
unsigned size {0};
int* p {nullptr};
};
A much simpler approach would be to use std::array<int>
and std::vector<int> instead of primitive C-style arrays.