template <typename Object>
class Sample {
public:
//assignment operator, copy constructor, etc. have been omitted but they work
Sample(size_t num) : array_{new Object[num]}, size_{num} { } //used for temp
void print(ostream & out) const {
for (unsignedint i = 0; i < size_; i++) {
out << array_[i] << " ";
}
}
void ReadSample() {
int count = 0;
cout << "Enter a size: ";
cin >> size_;
array_ = new Object[size_];
for (unsignedint i = 0; i < size_; i++) {
cout << "Enter element " << count + 1 << ": ";
cin >> array_[i];
count++;
}
}
size_t Size() const {
return size_;
}
Sample & operator+=(const Sample & rhs) {
Sample temp(size_ + rhs.size_);
for (unsignedint i = 0; i < size_; i++) {
temp.array_[i] = array_[i];
}
int j = 0;
for (unsignedint k = size_; k < size_ + rhs.size_; k++, j++) {
temp.array_[k] = rhs.array_[j];
}
*this = temp;
return *this;
}
Sample operator+(const Sample & rhs) const {
Sample temp(*this);
temp += rhs;
return temp;
}
~Sample() { //destructor
delete[] array_;
}
private:
size_t size_;
Object *array_;
};
template <typename Object>
ostream & operator<<(ostream & out, const Sample<Object> & rhs) {
rhs.print(out);
return out;
}
My main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main() {
Sample<string> a, b;
a.ReadSample();
cout << a << endl;
b.ReadSample();
cout << b << endl;
cout << a + b << endl;
Sample<string> d = a + b;
cout << d << endl;
cout << d + "adding this" << endl;
return 0;
}