【问题标题】:overloading ostream for any function that returns a vector为任何返回向量的函数重载 ostream
【发布时间】:2010-10-23 23:42:28
【问题描述】:

你好,假设我有 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;
 }
};

还有一些地方我重载了 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;
}

当我尝试时

A<int> obj;
cout<<obj.get_v; // gives soo many errors

但是当我这样做时

A<int> obj;
vector<int> v= obj.get_v;
cout<<v; // it works fine

我理解 ostream 重载有问题,或者我可能需要其他重载技术,有人可以帮我解决这个问题吗?提前致谢

【问题讨论】:

    标签: c++ templates operator-overloading reference


    【解决方案1】:

    您的 operator&lt;&lt; 重载采用非常量引用。您的A&lt;T&gt;::get_v() 函数按值返回std::vector&lt;T&gt;;这个返回的对象是临时的。非常量引用不能绑定到临时对象。

    您的重载需要使用 const 引用 (const std::vector&lt;T&gt;&amp;)。

    【讨论】:

    • 除了 James 所说的之外,对于这两个示例,如果您调用该函数会有所帮助。你只是指它。您的重载是针对向量,而不是针对返回向量的函数。干杯&hth.,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多