【问题标题】:how to overload << operator to output a vector that is a member of a class如何重载 << 运算符以输出作为类成员的向量
【发布时间】:2013-11-15 19:21:33
【问题描述】:

我正在尝试使用

编译器不允许我直接访问向量,因为它们是私有的,但它也不允许我访问返回向量的公共成员函数。

如何让

这是我的课:

class Name_pairs
{
    public:

    Name_pairs      (){}

    //....



    vector<string> Names       (){return names;      }
    vector<double> Ages        (){return ages;       }
    vector<double> Sorted_ages (){return sorted_ages;}


private:

    //....
    vector<string> names;
    vector<double> ages;
    vector<double> sorted_ages;
}; 

这是重载的

ostream& operator<<(ostream& os, const Name_pairs & n)
    {
        return os<< n.Names(); //won't let me access
            return os<< n.names.size(); //won't let me access 

    }

这是我试图通过重载

void Name_pairs:: print_name_age  ()
    {
        cout << endl << endl;
        cout << "These names and ages are now sorted" << endl;

        for(int index = 0; index <  names.size(); ++index)
            {
            cout << "index " << index << ": " << names[index]<< " is age: " << sorted_ages[index] <<endl;
            }

}

【问题讨论】:

    标签: c++ class vector overloading


    【解决方案1】:

    n.Names() 返回一个向量,您不能通过标准的operator &lt;&lt; 方法直接打印向量。您必须遍历向量并打印其元素。

    std::ostream& operator<<(std::ostream& os, const Name_pairs& n)
    {
        if (!os.good())
            return os;
    
        auto names = n.Names();
        std::copy(names.begin(), names.end(),
                                 std::ostream_iterator<std::string>(os));
        return os;
    }
    

    【讨论】:

    • std::ostream_iterator<:string>(os));当我将此代码放入我的
    • @user2904033 包含&lt;algorithm&gt;&lt;iterator&gt; 标头。
    【解决方案2】:

    线

    return os<< n.Names(); //won't let me access
    

    不起作用,因为您试图一次编写一个整个向量,而不是它的元素,并且ostream 没有为@987654324 提供重载的operator &lt;&lt; @。解决方案是从vector 中写入元素,该函数将返回这些元素。

    for(int i=0;i<n.Names().size();i++)
       cout << n.Names()[i];
    

    附带说明:您可能不希望将您的版本与大向量一起使用,因为(除非您的编译器足够聪明以使函数内联)会消耗大量时间返回整个向量。尝试将 const 引用返回到向量,而不是向量本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      相关资源
      最近更新 更多