Need help with part of code (operator overloading)

Okay so what our teacher gave us was this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  1. Develop a class smartArray with the following members: (5p)
public:
 int *elements // dynamic array, memory is allocated in the constructor. Use *this
 to access size member.
 int length() // returns the length of the array
 smartArray() // default constructor, sets size to 0
 smartArray(int size) // constructor, allocates the memory for *elements, if size==0, then
no memory allocation is done
 ~smartArray() // destructor
private:
 int size // number of the elements in the array


2. Overload << and >> operators (10p)
 overload operator << to print the array contents in the following format:
[33,66,23,63,75,23] (example)
 overload operator >> to read the array elements from the keyboard. Format:
enter element 1:
enter element 2:
etc. 


My problem with my code is I can't figure out how to use the length() function to return size and implement it into the code. What I have right now works but it's not using the length() function, its just using the this-> pointer for size.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>

using namespace std;

class smartArray {
public:
	int *elements;
	int length() {
		return size;
	}
	smartArray();
	smartArray(int);
	~smartArray() { delete[] elements; }
	friend ostream& operator <<(ostream& output, const smartArray &o);
	friend istream& operator >> (istream& input, const smartArray &o);
private:
	int size;
};
// overloaded >> operator
istream& operator >> (istream& input, const smartArray &o) {
	if (o.size != 0) {
		for (int i = 0; i < o.size; i++) {
			cout << "enter element " << i+1 << ":";
			input >> o.elements[i];
		}
	}
	return input;
}
// overloaded << operator
ostream& operator << (ostream& output, const smartArray &o) {
	for (int i = 0; i < o.size; i++) {
		if (i == 0)
			output << "[" << o.elements[i];
		else
			output << "," << o.elements[i];
	}
	cout << "]" << endl;
	return output;
}
//constructor
smartArray::smartArray() {
	size = 0;
}
// constructor w/ parameter
smartArray::smartArray(int size) {
	if (size != 0) {
		this->size = size;
		elements = new int[size];
	}
}

int main(){
	smartArray s1(15);
	cin >> s1;
	cout << s1;


}


hopefully someone can point me in the right direction.
Last edited on
Every time you add a value to the array, increment the size by 1.
Topic archived. No new replies allowed.