1. 首先我们需要知道const *p(常量指针)类型无法转换到*p类型(普通指针),但*p能够向const *p转换
#include<iostream>
using namespace std;
void const_fun( const int* a)
{
cout << "const fun" << endl;
}
void fun(int *a)
{
cout << "fun" << endl;
}
int main()
{
int *a=nullptr;
const_fun(a);
const int *b = nullptr;
fun(b); //*b为常量指针 无法转换为普通指针 报错
}
2. 于是我们还可以通过const来进行函数重载,使const p与p调用不同的函数
#include<iostream>
using namespace std;
void fun( const int* a)
{
cout << "const fun" << endl;
}
void fun(int *a)
{
cout << "fun" << endl;
}
int main()
{
int *a=nullptr;
fun(a);
const int *b = nullptr;
fun(b);
}
输出
fun
const fun
3. 与类对比
我们都知道类中函数都隐式传入了this指针,而常函数的作用就是修饰*this不能被修改
也就是 type fun(class *this) const就相当于type fun(const class *this)
于是类中就能存在type fun()与type fun() const两个函数,也就是重载了fun函数
常量对象传入函数的是const指针,普通对象传入的为普通指针。
而普通指针能向常量指针转换而常量指针无法向普通指针转换。
故普通成员能调用常函数,而常量成员无法调用普通函数。
#include<iostream>
using namespace std;
class A{
public:
void fun() const //相当于 void fun(const A *this)
{
cout << "fun const" << endl;
}
void fun() //相当于 void fun(A *this)
{
cout << "fun" << endl;
}
void test()
{
}
void test2() const
{
}
};
int main()
{
const A a;
A b;
a.fun();
b.fun();
//a.test(); //报错 常成员不能调用普通函数
b.test();
a.test2();
b.test2(); //常成员能调用const成员函数 因为普通指针能转换为常量指针
}
结果
fun const
fun
总结
- 我们可以通过常量指针与普通指针来重载函数
- 由于常量指针不能向普通指针转换,因此我们不能向参数为普通指针的函数传入常量指针。故我们不能通过const对象调用普通成员函数。
- 普通指针能转换为常量指针。故普通对象能调用普通函数也能调用常函数

京公网安备 11010502036488号