为什么下面的代码无法编译?
Why the following code doesn't compile?
我有以下C++代码:
#include <iostream>
#include <vector>
using namespace std;
class A
{
private:
int i;
public:
void f1(const A& o);
void f2()
{
cout<<i<<endl;
}
};
void A::f1(const A& o)
{
o.f2();
}
它就是不能编译。有人能解释一下吗?谢谢
大概是您的编译器告诉您为什么不编译。我说:
In member function ‘void A::f1(const A&)’:
passing ‘const A’ as ‘this’ argument of ‘void A::f2()’ discards qualifiers
这告诉我,您正在尝试对const
对象(const A& o
)的引用调用非const
成员函数(A::f2
)。
向函数添加const
限定符,以允许在const
对象上调用它:
void f2() const
^^^^^
或者从引用中删除const
以允许修改,但在这种情况下,不要这样做,因为f2()
不需要修改对象。
A::f2()
需要声明为const
才能从const
引用中使用。
更改:
void f2()
至:
void f2() const
不能在const
对象上调用非const
函数。通过将函数声明为const
,可以保证它不会更改对象的状态(mutable
成员变量除外)。
相关文章:
- 在Linux for Windows上编译C++代码时出错
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在程序中编写脚本来编写和编译代码
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 在macos上编译代码的未解析符号
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 使用指针编译代码后,.cpp文件将变为随机字符
- VS Express 无法正确编译代码(?
- 如何在Ubuntu中使用Visual Studio代码编译C++代码
- 使用 Android NDK 使用 clang++ 编译C++代码时对"_Unwind_Resume"的未定义引用
- 无法使用两个包装不同下一层的ssl_stream编译代码
- 编译代码时"[Warning] extra tokens at end of"
- 无法编译代码,因为它已在 C++11 中弃用
- 如何在 Azure 应用服务中使用 cl.exe 编译 C++ 代码并生成可执行文件
- 如何调试编译 c++ 代码的 bazel?
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 编译 C++ 代码后尺寸较大
- 使用用 C++ 和 DDS 编写的 CMAKE 编译代码
- 编译代码时如何不制作二进制文件?
- 如何使用所有其他文件信息来编译代码,例如HAAR级联训练的权重的XML文件