const和非no_const成员函数的调用主要正对const和非const变:
#include<iostream>
using namespace std;
class A
{
public:
void f() const { cout << "const" << endl; }
void f() { cout << "no-const" << endl; }
private:
int a;
};
int main()
{
A a1;
a1.f();
const A a2;
a2.f();
system("pause");
return 0;
}
注意:
下面我们对一些细节讨论
1.只有const函数或者只有非const函数
#include<iostream>
using namespace std;
class A
{
public:
void f() const { cout << "const" << endl; }
//void f() { cout << "no-const" << endl; }
private:
int a;
};
int main()
{
A a1;
a1.f();
const A a2;
a2.f();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
class A
{
public:
//void f() const { cout << "const" << endl; }
void f() { cout << "no-const" << endl; }
private:
int a;
};
int main()
{
A a1;
a1.f();
const A a2;
a2.f();//对象含有与成员 函数 "A::f" 不兼容的类型限定符
system("pause");
return 0;
}
报错了。
2 cont成员函数不能修改类中定义的变量。
class A
{
public:
void f() const { num = 100; }//compile_time;表达式必须是可修改的左值
void f() { num = 100; }//ok
private:
int num;
};
报错了。但是我们可以使用关键字mutable来强制完成上面工作;
class A
{
public:
void f() const { num = 100; }
void f() { num = 100; }
private:
mutable int num;
};
这样就ok了
总结:
no_const的变量可以调用const和no_const成员函数(两者都有的话,优先调用no_const成员函数)。const变量只能调用const成员函数,如果没有就会报错。
小技巧
因为const成员函数的