插入操作符,const关键字导致编译错误

C++ - Insertion Operator, const Keyword Causes Compiler Error

本文关键字:编译 错误 关键字 操作符 const 插入      更新时间:2023-10-16

我正在构建一个类,为了简单起见,我在这里简化它

这会给出一个编译器错误:"错误:对象具有与成员函数不兼容的类型限定符。"

这是代码:

ostream& operator<<(ostream& out, const Foo& f)
{
    for (int i = 0; i < f.size(); i++)
        out << f.at(i) << ", ";
    out << endl;
    return out;
}

at(int i)函数返回索引为i的数组的值。

如果我从Foo中删除const关键字,一切都工作得很好。为什么?

编辑:每个请求,成员函数的声明。

. h

public:
    int size(void);
    int at(int);

. cpp

  int Foo::size()
    {
       return _size; //_size is a private int to keep track size of an array.
    }
    int Foo::at(int i)
    {
       return data[i]; //where data is an array, in this case of ints
    }

你需要声明你的"at"函数和"size"函数为const,否则它们不能作用于const对象。

那么,你的函数可能看起来像这样:

int Foo::at(int i)
{
     // whatever
}

它需要看起来像这样:

int Foo::at(int i) const
{
     // whatever
}

你正在调用一个函数来改变一个常量对象上的对象。您必须确保函数at不会通过将其声明为const来改变类Foo的对象(或删除参数中的const以允许at做它所做的事情,如果它确实需要改变Foo中的一些内部数据)。