【发布时间】:2015-02-08 23:48:29
【问题描述】:
我试图通过重载运算符
打印输出应为 1 2 3 4。
但它实际上会打印出如下内容:28495936 0 3 4。
应该被推入向量的前两个元素(例如 1 和 2)丢失或被污染。
如果有人能帮我弄清楚这背后的原因,我将不胜感激。
#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;
}
【问题讨论】:
标签: c++ vector type-conversion operator-overloading push-back