C++——插入运算符、const关键字导致编译器错误

标签 c++ operator-overloading constants

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

这会产生编译器错误:“错误:对象具有与成员函数不兼容的类型限定符。”

这是代码:

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
}

关于C++——插入运算符、const关键字导致编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5589361/

相关文章:

c++ - 多维数组 - malloc 与 new

c++ - 如何删除类中的实例类

c++ - 重载运算符必须采用零个或一个参数

带 1 个参数的 C++ 2D 数组索引(为什么这行得通?)

不能声明一个 size=var 的字符串,即使 var 是 const

c++ - 在成员函数之间传递 const 变量作为数组的索引

c++ - 断言 unsigned int a indeed positive 不起作用?

c++ - "Remember the milk"订阅日历的 Google 日历同步问题

groovy - 重载 Groovy 比较运算符的问题

c++ - 我应该返回 bool 还是 const bool?