gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:53:20 25 4
gpt4 key购买 nike

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

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

当我在上面一行输入时,出现编译器错误 invalid operands to binary expression

最佳答案

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

但是参数是const , 所以它不能传递到你的 operator<< ! const&不绑定(bind)到 & .这就是编译器提示的原因。你必须把它标记为const& :

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

这也是一个好习惯:您不会修改 obj , 所以你没有理由不把它标记为 const .

关于c++ - Std::copy 和 std::ostream_iterator 使用重载函数打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com