[C++] const与重载

时间:2023-11-24 18:01:56

下面的两个函数构成重载吗?

void M(int a){} //(1)
void M(const int a){} //(2)

下面的呢?

void M(int& a){} //(3)
void M(const int& a){} //(4)
const在函数中的含义是该值在此函数范围内“无法修改”。站在调用者的角度,所有的值传递都是无法修改实参的。所以,(1)/(2)两个函数在调用者看来,是语义相同的,不能构成重载。
(4)与(3)的区别是,(4)无法修改引用指向的对象,而(3)可以。从调用者的角度,两个函数有不同的语义,构成重载。
demo 
 #include <iostream>
using namespace std; class Y{}; /* 下面两个函数具有相同语义,即a均是值拷贝,无法改变实参。 */
void Method1(int a){}
void Method1(const int a){} // error:redefinition /* 同样的语义,对象拷贝 */
void Method2(Y y){}
void Method2(const Y y){} // error:redefinition /* 下面两个函数具有不同语义,即后者无法改变实参,之所以使用引用,可能是因为不想拷贝,节省内存。 */
void Method3(int& a){}
void Method3(const int& a){} void Method4(Y& y){}
void Method4(const Y& y){} int main(int count,char * args[])
{
return ;
}