c++ - 通过交换参数顺序的函数重载

标签 c++ language-lawyer overloading

关于 C++ 中的函数覆盖,以下是合法的,因为两个原型(prototype)具有不同数量的参数:

void func(int par1, double par2);
void func(int par1, double par2, double par3);

原样(因为至少有 1 个不同类型的参数):

void func(int par1, double par2);
void func(double par1, double par2);

我想知道,只是出于好奇,是否可以重载相同数量、相同类型但顺序不同的参数?例如以下是合法的:

void func(int par1, double par2);
void func(double par1, int par2);

如果有,有没有正式文件说明?

最佳答案

正式文件是 ISO C++ 标准,是的,你可以做到。

整个 ISO C++11 第 13 章都致力于重载,但前几段很好地总结了这一点:

When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded. By extension, two declarations in the same scope that declare the same name but with different types are called overloaded declarations. Only function and function template declarations can be overloaded; variable and type declarations cannot be overloaded.

When an overloaded function name is used in a call, which overloaded function declaration is being referenced is determined by comparing the types of the arguments at the point of use with the types of the parameters in the overloaded declarations that are visible at the point of use.

如果参数列表不同,包括顺序,则可以重载。您在问题中提出的所有三种情况都是不同的:

{int, double} vs {int, double, double}
{int, double} vs {double, double}
{int, double} vs {double, int}

请注意,这两个函数不能重载:

void func(int par1, int par2);
void func(int par2, int par1);

因为实际上只有类型 提供了唯一性,而不是参数名称。这两个函数都称为 func 并且它们都有参数列表 {int, int},因此它们不是唯一的。

关于c++ - 通过交换参数顺序的函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25840328/

相关文章:

c++ - 有谁知道 C++ 中简单而灵活的 2d 场景图?

C++自动推导模板成员指针的类型

c++ - 在函数中使用时自己的 operator+ 的奇怪行为(Point3D(0,0,0)+ 点)

c++ - 为什么 c++ 的命名空间范围还包括文件范围(在 c 中)?

c++ - 不可移动对象数组的初始化 : why does such code fail to compile on GCC?

c++ - 我可以根据属性重载函数模板吗?

actionscript-3 - AS3 : Can we skip an optional parameter and assign value to the parameter after the skipped one?

c++ - 警告 : conversion from string literal to 'char *' is deprecated

c++ - 如何一劳永逸地在VS中设置配置属性?

c++ - 转发声明 opengl 类型