Ism*_*ush 1 c++ templates reference operator-overloading
嗨,假设我有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;
}
};
Run Code Online (Sandbox Code Playgroud)
还有一些地方我重载了std :: vector的ostream
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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试
A<int> obj;
cout<<obj.get_v; // gives soo many errors
Run Code Online (Sandbox Code Playgroud)
但是当我这样做的时候
A<int> obj;
vector<int> v= obj.get_v;
cout<<v; // it works fine
Run Code Online (Sandbox Code Playgroud)
我理解ostream重载有问题,或者我可能需要其他重载技术,有人可以帮助我吗?提前致谢
您的operator<<重载采用非const引用.你的A<T>::get_v()函数返回一个std::vector<T>by值; 这个返回的对象是临时的.非const引用不能绑定到临时对象.
你的重载需要采用const引用(const std::vector<T>&).