赞
踩
const 修饰函数有三种:
const
T Foo::bar( const
T ) const
;
函数返回值不能作为区分函数重载的因素
如:
void foo( int );
void foo( const int );
如果以上这两个函数是在一个作用域内,函数重载失败,编译报错。
既,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
以上例外const必须修饰的是指针指向的内容, 既ponter-to-const;
如果是指针本身是const的,则不能重载, 如:
void foo( int* );
void foo( int* const ); // compile error
如:
class A {
//...
public:
void foo(); // 1
void foo() const; // 2
};
//...
A a;
const A ca;
a.foo(); // call #1
ca.foo(); // call #2
类的成员函数隐含会传递this指针; 而const成员函数则传递const this指针。调用哪一个取决于类的对象是否是const的。
Ref:
https://www.geeksforgeeks.org/function-overloading-in-c/?ref=lbp
https://blog.csdn.net/zjcxhswill/article/details/50640214
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。