【问题标题】:C++ ostream operator overloading using const argument error使用 const 参数错误的 C++ ostream 运算符重载
【发布时间】:2013-04-01 22:09:14
【问题描述】:

我正在尝试为 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,这会正常工作,否则会出现上述错误。我没有为该类定义赋值运算符,但我不清楚为什么这会有所作为。

【问题讨论】:

    标签: constants overloading operator-keyword


    【解决方案1】:

    那是因为您尝试使用非 const 迭代器来迭代 const 对象。将j的声明改为:

    std::vector<owComponent>::const_iterator j;
    

    或者只使用 C++11 风格:

    for (auto j : bus.owCompList) {
    

    【讨论】:

    • 谢谢,我尝试将迭代器设为 const,但没有正确执行。 RTFM 恐怕...
    猜你喜欢
    • 2014-04-24
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多