C++ - 插入运算符、const关键字导致编译错误
所以我正在构建一个类,为了简单起见,我将在这里简化它。
这会产生编译器错误:“错误:对象具有与成员函数不兼容的类型限定符。”
代码如下:
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.cpp
public:
int size(void);
int at(int);
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
}
So I'm building a class, for simplicity, I'll dumb it down here.
This gives a compiler error: "Error: the object has type qualifiers that are not compatible with the member function."
This is the code:
ostream& operator<<(ostream& out, const Foo& f)
{
for (int i = 0; i < f.size(); i++)
out << f.at(i) << ", ";
out << endl;
return out;
}
the at(int i) functions returns a value from an array at index i.
If I remove the const keyword from Foo, everything works great. Why?
EDIT: Per request, the declarations for the member functions.
.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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将“at”函数和“size”函数声明为const,否则它们无法作用于const 对象。
所以,你的函数可能看起来像这样:
并且它需要看起来像这样:
You need to declare your "at" function and your "size" function as const, otherwise they cannot act on const objects.
So, your function might look something like this:
And it needs to look like this:
您正在调用一个更改常量对象上的对象的函数。您必须确保函数
at
不会通过将类Foo
的对象声明为const
来更改该对象(或者删除Foo
类的对象)(或者删除Foo
类的对象)。 >const 参数中允许at
执行任何操作(如果它确实需要更改Foo
中的某些内部数据)。You're calling a function which changes the object on a constant object. You have to make sure that the function
at
doesn't change the object of classFoo
by declaring it asconst
(or remove theconst
in the parameter to allowat
do whatever it does if it does indeed need to change some internal data inFoo
).