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

样品

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

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, " "));

但是说我有Employee类和重载运算符<<

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

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

火箭1111

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

但是参数为const,因此无法将其传递给您operator<<Aconst&不绑定到&这就是编译器抱怨的原因。您将必须对其进行标记const&

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章