如何重载<<运算符以输出作为类成员的向量

时间:2013-11-15 19:21:34

标签: c++ class vector overloading

我正在尝试使用<<运算符输出属于我的类的私有成员的向量。

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

如何制作<< operator输出私有成员向量的所有内容?

这是我的班级:

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;
}; 

这是重载的&lt;&lt;功能:

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 

    }

这是我试图通过重载&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;功能:

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;
            }

}

2 个答案:

答案 0 :(得分:2)

n.Names()返回一个向量,您无法通过标准operator <<方法直接打印向量。你必须遍历向量并打印它的元素。

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;
}

答案 1 :(得分:1)

该行

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

不起作用,因为你一次尝试写一个整个矢量,而不是它的元素,而ostream没有&#39 ; t为operator <<提供了重载std::vector。解决方案只是编写vector中的元素,这个函数返回了这些元素。

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

作为旁注:您可能不希望将您的版本与大型向量一起使用,因为(除非您的编译器足够聪明以使函数内联),否则会消耗很多时间返回整个矢量。尝试将 const引用返回给向量,而不是向量本身。