插入操作符,const关键字导致编译错误
C++ - Insertion Operator, const Keyword Causes Compiler Error
我正在构建一个类,为了简单起见,我在这里简化它
这会给出一个编译器错误:"错误:对象具有与成员函数不兼容的类型限定符。"
这是代码:
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
中的一些内部数据)。
相关文章:
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?