Div*_*Vox 1 c++ const operator-overloading
所以我正在建立一个班级,为简单起见,我会在这里愚蠢.
这给出了编译器错误:"错误:对象具有与成员函数不兼容的类型限定符."
这是代码:
ostream& operator<<(ostream& out, const Foo& f)
{
for (int i = 0; i < f.size(); i++)
out << f.at(i) << ", ";
out << endl;
return out;
}
Run Code Online (Sandbox Code Playgroud)
at(int i)函数从索引i处的数组返回一个值.
如果我从Foo中删除const关键字,一切都很好.为什么?
编辑:每个请求,成员函数的声明.
.H
public:
int size(void);
int at(int);
Run Code Online (Sandbox Code Playgroud)
的.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
}
Run Code Online (Sandbox Code Playgroud)
您需要将"at"函数和"size"函数声明为const,否则它们不能作用于const对象.
所以,你的函数可能看起来像这样:
int Foo::at(int i)
{
// whatever
}
Run Code Online (Sandbox Code Playgroud)
它需要看起来像这样:
int Foo::at(int i) const
{
// whatever
}
Run Code Online (Sandbox Code Playgroud)