常成员函数不能修改(设置)对象的数据成员,只能访问数据成员。 常成员函数中只能调用常成员函数。 通过常对象只能调用常成员函数,通过常对象不能调用一般成员函数(非常成员函数)。 通过一般对象也可以调用常成员函数。
//HW_CH03_22(3)
#include<iostream>
using namespace std;
class Sample {
private:
int a;
int b;
public:
Sample(int x, int y) {
a = x, b = y;
}
void seta(int x) {
a = x;
}
void display() {
cout << "a=" << a << ",b=" << b << endl;
}
};
int main() {
Sample obj(100, 200);
obj.seta(0);//E1086 对象含有与成员 函数 "Sample::seta" 不兼容的类型限定符
obj.display();
return 0;
}
/*
class Sample {
private:
int a;
const int b;
public:
Sample(int x, int y) {
a = x, b = y;
}
void seta(int x) {
a = x;
}
void display() {
cout << "a=" << a << ",b=" << b << endl;
}
};
int main() {
const Sample obj(100, 200);
obj.seta(0);//E1086 对象含有与成员 函数 "Sample::seta" 不兼容的类型限定符
obj.display();
}
*/