I am trying to make a vector out of several integers by overloading the operator << and conversion operator. However, when I test my code, I observe some absurd results.
The printed output should be 1 2 3 4.
But it actually print out something like this: 28495936 0 3 4.
The first two elements (e.g, 1 and 2) that were supposed to be pushed into the vector is lost or polluted.
I would appreciate it if someone can help me to figure it out the reason behind this.
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<<(const T& val)
{
data_.push_back(val);
return *this;
}
operator std::vector<T>&()
{
return this->data_;
}
private:
std::vector<T> data_;
};
int main() {
std::vector<int>& A2 = make_vector<int>() << 1 << 2 << 3 << 4;
for (std::vector<int>::iterator it = A2.begin(); it != A2.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
return 0;
}