I know operator overloading can assign an object of data type X into another object of the same datatype.
like int a=1; int b; b=a;
My question is if it's possible to do the following:
int array[3] = {1,2,4}
Then how do I program my class to do the same?
You may be looking for an "initializer_list".
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
|
#include <iostream>
#include <initializer_list>
using namespace std;
template <typename T>
class Array {
T* m_a;
size_t m_size;
public:
Array(initializer_list<T> il)
: m_size(il.size())
{
T* p = m_a = new T[m_size];
for (const T& n: il) *p++ = n;
}
~Array() { delete [] m_a; }
size_t size() const { return m_size; }
ostream& print(ostream& os) const
{
for (size_t i = 0; i < m_size; i++)
os << m_a[i] << ' ';
return os;
}
};
template <typename T>
ostream& operator<<(ostream& os, const Array<T>& a) {
return a.print(os);
}
int main() {
int a[]{1, 2, 3, 4, 5};
for (int n: a) cout << n << ' ';
cout << '\n';
Array<int> arr{6, 7, 8, 9, 0};
cout << arr << '\n';
}
|
Last edited on