qfedu-cpp-level/day4/d4.cpp

39 lines
977 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 当const修饰成员函数时函数内不能修改普通成员变量但可以修改mutable修饰的成员变量。 当const修饰类对象时只能读成员变量不能修改成员变量的值。可以调用const修饰的成员函数
// 能调用普通成员函数
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class A
{
public:
int x;
mutable int y;
public:
void setXY(int x, int y) const
{
// this->x = x; // error
this->y = y;
}
void show()
{
cout << x << ", " << y << endl;
}
};
int main()
{
A a1;
a1.setXY(1, 2); // const 函数,内部不修改非 mutable 的成员变量
a1.show();
// const A a2; // 报错const 变量必须存在初始值(右值)
const A a2 = A();
a2.setXY(0, 30); // const 对象可以访问 const 的成员函数
// a2.show(); // const 对象不能访问非 const 成员函数
return 0;
}