提问人:Abhishek Mane 提问时间:10/4/2021 最后编辑:JeJoAbhishek Mane 更新时间:10/4/2021 访问量:556
通过 const 限定对象调用成员函数会给出错误,因为函数未标记为 const?
Calling member function through const qualified object gives error as function is not marked as const?
问:
法典
#include <iostream>
class A
{
public:
mutable int x;
mutable int y;
A(int k1 = 0, int k2 = 0) :x(k1), y(k2) {}
void display()
{
std::cout << x << "," << y << "\n";
}
};
int main()
{
const A a1;
a1.x = 3;
a1.y = 8;
a1.display();
return 0;
}
输出
Error: 'this' argument to member function 'display'
has type 'const A', but function is not marked const
我只是通过限定对象调用成员函数。那么为什么行会给出错误呢?A::display()
const
a1
a1.display()
答:
5赞
JeJo
10/4/2021
#1
为什么行给出错误?
a1.display()
该变量允许您修改限定函数中的成员变量。mutable
const
它不允许你调用要通过限定实例调用的限定成员函数。因此,您需要在那里使用成员函数。non-const
const
const
评论
mutable
const
x
y
a1
const A a1(3, 8);
mutable
非私人成员可疑