当前位置:   article > 正文

C++ const与函数重载_const能用于区分重载吗

const能用于区分重载吗

const 修饰函数有三种:
const T Foo::bar( const T ) const;

1. 修饰函数返回值

函数返回值不能作为区分函数重载的因素

2. 修饰函数参数

如:

void foo( int );
void foo( const int );
  • 1
  • 2

如果以上这两个函数是在一个作用域内,函数重载失败,编译报错。

既,const修饰 函数参数一般不作为区分重载的因素。

但有例外:const修饰的函数参数是指针引用时,可以重载,如:

void foo( char* ); // 1
void foo( const char* ) ; //2
void foo( char& ); // 3
void foo( const char& ); // 4
//...
char str[] = "hello";
const char cstr[] = "world";
foo( str ); // call #1 foo
foo( cstr ); // call #2 foo
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

以上例外const必须修饰的是指针指向的内容, 既ponter-to-const;

如果是指针本身是const的,则不能重载, 如:

void foo( int* );
void foo( int* const ); // compile error
  • 1
  • 2
3. 修饰类的成员函数

如:

class A {
//...
public:
	void foo(); // 1
	void foo() const; // 2
};
//...
A a;
const A ca;
a.foo(); // call #1
ca.foo(); // call #2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

类的成员函数隐含会传递this指针; 而const成员函数则传递const this指针。调用哪一个取决于类的对象是否是const的。

Ref:
https://www.geeksforgeeks.org/function-overloading-in-c/?ref=lbp
https://blog.csdn.net/zjcxhswill/article/details/50640214

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/838263
推荐阅读
相关标签
  

闽ICP备14008679号