我正在尝试将标准格式用于 ostream 运算符的非成员函数重载,但是当我对向量迭代器进行内部赋值时,它不适用于 const 第二个参数。当使用 const 参数时,编译器会给出以下错误:error: no match for 'operator=' in j = bus.owAPI::owBus::owCompList.std::vector...
我的类的相关部分如下:
class owBus{
public:
std::vector<owComponent> owCompList; //unsorted complete list
friend std::ostream&
operator<<(std::ostream& os, const owBus& bus );
};
使用非成员函数:
std::ostream& operator<<(std::ostream& os, const owBus& bus ) {
//iterate through component vector
std::vector<owComponent>::iterator j;
for(j=bus.owCompList.begin(); j!=bus.owCompList.end(); j++) {
/*
os << (*j).getComponentID() << ": ";
os << (*j).getComponentType() << std::endl;
*/
}
return os;
}
如果从友元声明和函数描述中的第二个参数中删除了 const,则此方法可以正常工作,否则会出现上述错误。我没有为该类定义赋值运算符,但我不清楚为什么这会有所作为。