在C ++中重载的概念 [英] concept of overloading in C++

查看:156
本文介绍了在C ++中重载的概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

case 1:
你可以重载两个函数,即:
$ b $ pre $ void foo(int *);
void foo(const int *);


情况2:
您不能重载两个函数:

  void foo(int); 
void foo(const int);

我已经编码并检查了这个概念,但却无法找出造成这种重载变化的原因。

解决方案

从标准§13.1 $ b


仅在 存在或不存在
const和/或volatile的参数声明是等同的
。也就是说,当确定
哪个函数被声明,定义或调用时,忽略每个参数类型的const和volatile
类型说明符。 [例子:



  typedef const int cInt; 
int f(int);
int f(const int); //重新声明f(int)
int f(int){/ * ... * /} //定义f(int)
int f(cInt){/ * ... * /} //错误:重新定义f(int)




-end例子]

只有在
参数类型规范最外层的const和volatile类型说明符以这种方式被忽略; const
和嵌入参数类型
规范中的易失性类型说明符是重要的,可用于区分
重载函数声明。特别是,对于任何类型T,
指向T的指针,指向const T的指针, 和指向volatile T的指针
被认为是不同的参数类型,
正如引用T,
引用const T,引用volatile T。



case 1: you can overload two functions namely:

void foo(int *);
void foo(const int *);

while in , case 2: you can not overload two functions:

void foo(int);
void foo(const int);

I have coded and checked this concept and yet unable to find out the reason to this variation in overloading.

解决方案

From Standard §13.1

Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called. [ Example:

typedef const int cInt;
int f (int);
int f (const int); // redeclaration of f(int)
int f (int) { /* ... */ } // definition of f(int)
int f (cInt) { /* ... */ } // error: redefinition of f(int)

—end example ]

Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations. In particular, for any type T, "pointer to T," "pointer to const T," and "pointer to volatile T" are considered distinct parameter types, as are "reference to T," "reference to const T," and "reference to volatile T."

这篇关于在C ++中重载的概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆