博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++函数重载(2) - 不能被重载的函数
阅读量:4071 次
发布时间:2019-05-25

本文共 1976 字,大约阅读时间需要 6 分钟。

C++中,符合下面这些情况的函数不能被重载。
 
1) 仅仅是返回值不同
例如,下面的程序会编译失败。
#include
int foo() { return 10;}char foo() { return 'a';}int main(){ char x = foo(); getchar(); return 0;}
2) 成员函数名称以及参数完全相同,仅仅其中一个是static成员函数。
例如,下面程序会编译失败。
#include
class Test { static void fun(int i) {} void fun(int i) {}};int main(){ Test t; getchar(); return 0;}
3) 函数参数仅仅是指针与数组的差别。这样实际上是相等的。
例如,下面程序会编译失败。
int fun(int *ptr);int fun(int ptr[]);  //相当于fun(int *ptr)的重复声明
4) 函数差别仅在于参数类型,其中一个是函数类型,另一个是相同类型的函数指针。这样实际上是相等的。
例如,下面程序会编译失败。
void h(int ());void h(int (*)()); //相当于h(int())的重复声明
如果只是这样的声明两个函数,也许可以编译通过。但是,写上函数主体后,如下所示,编译会报错。
void h(int()){}void h(int(*)()){}
visual studio 2015编译器提示:“error C2084: 函数“void h(int (__cdecl *)(void))”已有主体”
 
5) 函数参数差别仅在于有无const或volatile。
当编译器决定哪个函数被声明,定义或调用时,每个参数的const和volatile类型修饰会被忽略掉。
例如,下面的程序会编译失败,提示error “redefinition of `int f(int)’ ”
#include
#include
using namespace std;int f ( int x) { return x+10;}int f ( const int x) { return x+10;}int main() { getchar(); return 0;}
只有当const和volatile是在参数类型修饰的最外层(左侧)使用时,编译器才会进行区别;如果const和volatile被包围在了参数类型修饰的里边,则不能用来区分重载函数声明。特别地,对于任意类型T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” 可以用来区别参数类型, 后面的引用也同样如此, “reference to T,” “reference to const T,” and “reference to volatile T.” 具体参加下面例子:
 
void f(int * x)
void f(const int *x)或void f(int const *x)   // 编译正常
但是,第二个不能为void f(int * const x)
 
void f(int * x)
void f(volatile int *x)或void f(int volatile *x)   // 编译正常
但是,第二个不能为void f(int * volatile x)
 
void f(int& x)
void f(const int& x)或void f(int const &x)  //编译正常
但是,第二个不能为void f(int & const x)   //这样写本身就不合法
 
6) 函数之间的差别仅在于默认参数值的不同。这样实际上也是相等的. 
例如,下面程序会编译错误“redefinition of `int f(int, int)’ “
#include
#include
using namespace std;int f ( int x, int y) { return x+10;}int f ( int x, int y = 10) { return x+y;}int main() { getchar(); return 0;}
参考文献:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf

转载地址:http://qmeji.baihongyu.com/

你可能感兴趣的文章
将file文件内容转成字符串
查看>>
循环队列---数据结构和算法
查看>>
优先级队列-数据结构和算法
查看>>
链接点--数据结构和算法
查看>>
servlet中请求转发(forword)与重定向(sendredirect)的区别
查看>>
Spring4的IoC和DI的区别
查看>>
springcloud 的eureka服务注册demo
查看>>
eureka-client.properties文件配置
查看>>
MODULE_DEVICE_TABLE的理解
查看>>
platform_device与platform_driver
查看>>
platform_driver平台驱动注册和注销过程(下)
查看>>
.net强制退出主窗口的方法——Application.Exit()方法和Environment.Exit(0)方法
查看>>
c# 如何调用win8自带的屏幕键盘(非osk.exe)
查看>>
build/envsetup.sh 简介
查看>>
C++后继有人——D语言
查看>>
Android framework中修改或者添加资源无变化或编译不通过问题详解
查看>>
linux怎么切换到root里面?
查看>>
linux串口操作及设置详解
查看>>
安装alien,DEB与RPM互换
查看>>
linux系统下怎么安装.deb文件?
查看>>