C++中const用于函数重载的示例代码

2020-01-06 17:42:56于海丽

常成员函数和非常成员函数之间的重载

首先先回忆一下常成员函数

声明:<类型标志符>函数名(参数表)const;

说明:

(1)const是函数类型的一部分,在实现部分也要带该关键字。

(2)const关键字可以用于对重载函数的区分。

(3)常成员函数不能更新类的成员变量,也不能调用该类中没有用const修饰的成员函数,只能调用常成员函数。

(4)非常量对象也可以调用常成员函数,但是如果有重载的非常成员函数则会调用非常成员函数。

重载看例子:


#include<iostream> 
using namespace std; 
class Test 
{ 
protected: 
  int x; 
public: 
  Test (int i):x(i) { } 
  void fun() const 
  { 
    cout << "fun() const called " << endl; 
  } 
  void fun() 
  { 
    cout << "fun() called " << endl; 
  } 
}; 
int main() 
{ 
  Test t1 (10); 
  const Test t2 (20); 
  t1.fun(); 
  t2.fun(); 
  return 0; 
} 

结果为:

c++,const函数,const函数重载

const修饰成员函数时的重载

分两种情况,一种情况下不允许重载,另一种允许。还是直接看例子吧:


#include<iostream> 
using namespace std; 
void fun(const int i) 
{ 
  cout << "fun(const int) called "; 
} 
void fun(int i) 
{ 
  cout << "fun(int ) called " ; 
} 
int main() 
{ 
  const int i = 10; 
  fun(i); 
  return 0; 
} 

结果:编译错误,提示重定义:

c++,const函数,const函数重载

其实很好理解:


void fun(int a)和
void fun(const int a);

实际上没有区别,因为函数调用的时候,存在形实结合的过程,所以不管有没有const都不会改变实参的值。

但是看下面的情况:


#include<iostream> 
using namespace std; 
void fun(char *a) 
{ 
 cout << "non-const fun() " << a; 
} 
void fun(const char *a) 
{ 
 cout << "const fun() " << a; 
} 
int main() 
{ 
 const char *ptr = "hello world"; 
 fun(ptr); 
 return 0; 
}