overloading ostream for any function that returns a vector
Hi assume that I have class A :
using namespace std;
template <class T>
class A{
private:
vector<T> my_V;
public:
// assume initializations etc are done
inline vector<T> get_v()
{
return my_v;
}
};
and some where else I 开发者_如何学Gohave overloaded ostream of std::vector
template <class T>
ostream & operator<<(ostream& out, vector<T> &vec)
{
CUI size=vec.size();
for (int i = 0; i < size; i++)
out << vec.at(i) << " ";
if(size>0)out << endl;
return out;
}
when I try to
A<int> obj;
cout<<obj.get_v; // gives soo many errors
but when I do
A<int> obj;
vector<int> v= obj.get_v;
cout<<v; // it works fine
I understand something wrong with the ostream overloading or I might need other overloading technique can someone please help me with that ? Thanks in advance
Your operator<<
overload takes a non-const reference. Your A<T>::get_v()
function returns a std::vector<T>
by value; this returned object is a temporary. A non-const reference cannot bind to a temporary object.
Your overload needs to take a const reference (const std::vector<T>&
).
精彩评论