Std::copy 和 std::ostream_iterator 使用重载函数打印值

Std::copy and std::ostream_iterator to use overloading function to print values

我想知道如何使用 std::copy 来使用我的 class 的重载运算符。 例如要打印 int 类型的向量,我们可以使用这样的东西

std::vector<int> vec{ -1, 4, 70, -5, 34, 21, 2, 58, 0 , 34 , 27 , 4 };
std::copy( vec.begin(), vec.end(), std::ostream_iterator<int>( std::cout, " "));

但是假设我有 class 员工和重载运算符 <<

class Employee
{

public:
    Employee( const string _name, const string _last, const int _sal ):
        name(_name),
        lastname(_last),
        salary(_sal )
    {

    }
friend ostream& operator<<(ostream&os,  Employee&obj )
{
    return os << obj.name << " "<< obj.salary;
}

private:
    std::string name;
    std::string lastname;
    int salary;

};

那我怎么用std::copy来用ostream_iterator打印员工姓名和薪水例子

 int main()
{
    std::vector<Employee> staff
     {
         {"tim", "sim", 1000 },
         {"dave", "ark", 2000 },
         {"kate", "Greg", 2000 },
         {"miller", "jane", 1000 },
         {"wht", "Up", 2000 }

     };

 std::copy( begin( staff), end(staff), std::ostream_iterator<Employee>( cout, " ")); // How to use this line ???
 return 0;
}

当我在上面的行中键入时,出现编译器错误二进制表达式的无效操作数

std::ostream_iterator::operator=的参数为const&。在内部,这将使用 operator<< 将每个值输出到流中。

但是参数是const,所以不能传入你的operator<<const& 不绑定到 &。这就是编译器抱怨的原因。您必须将其标记为 const&:

friend ostream& operator<<(ostream&os,  const Employee& obj )
{
    return os << obj.name << " "<< obj.salary;
}

这也是一个好习惯:您不会修改 obj,因此您没有理由不将其标记为 const