所以我正在构建一个类,为了简单起见,我将在这里简化它。
这会产生编译器错误:“错误:对象具有与成员函数不兼容的类型限定符。”
这是代码:
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/