c++ - 为什么这两个函数不能重载呢?

标签 c++ overloading

<分区>

为什么我不能重载这两个函数?

#include <iostream>
using namespace std;

class Base
{
    public:
    void run(int a);
    void run(const int a);
};
int main() {
    // your code goes here
    return 0;
}

输出:

prog.cpp:8:7: error: 'void Base::run(int)' cannot be overloaded
  void run(const int a);
       ^
prog.cpp:7:7: error: with 'void Base::run(int)'
  void run(int a);

最佳答案

根据标准:

13.1 Overloadable declarations
....

(3.4) — 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++ - 为什么这两个函数不能重载呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896991/

相关文章:

java - 解释在 Kotlin 方法上使用 @JvmOverloads 生成的 Java 代码

c++ - 虚继承中的重载虚函数

java - 在 Java 中重写方法有哪些不同的方式?

c++ - 模板特化和函数重载之间的区别?

c++ - 在按钮中实例化类的范围问题

c++ - 可移植网格引擎平台

c++ - Geotiff坐标转换错误

c# - 将 NULL 传递给构造函数

c++ - 比较来自一个 vector 的迭代器时,什么会引发 'iterators are incompatible'?

c++ - 如何设置对象转换、属性?