c++ - 函数重载和方法重载的区别

标签 c++ c oop overloading

您好,我想了解 C++ 中函数重载和方法重载之间的区别。谷歌搜索后我发现了这个。不确定这是否正确。如有错误请指正。

Method overloading and function overloading are related concepts. The term method overloading is defined as a feature which is found in various programming languages such as C++ and Java. It permits the creation of various functions with the same name. However all these functions differ from each other in terms of the type of input and the type of output of the function.

On the other hand, the term function overloading is used in object-oriented programming. It is defined as a technique in which two or more functions which have the same name are distinguished from one another using different numbers and/or types of parameters.

来源:http://www.blurtit.com/q662319.html

最佳答案

在 C++ 中,方法 通常用于引用类或结构的成员函数,同时,
Function 是一个独立的非成员函数。


标准如何声明函数和方法?

根据 C++ 标准,函数声明定义在: 8.3.5 函数[dcl.fct]

In a declaration T D where D has the form

D1 ( parameter-declaration-clause ) cv-qualifier-seqopt exception-specificationopt

and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-listT,” the type of the declarator-id in D is “derived-declarator-type-list function of (parameter-declaration-clause) cv-qualifier-seqopt returning T”; a type of this form is a function type86).

请注意,该标准在 #4 中进一步说明:

A cv-qualifier-seq shall only be part of the function type for a nonstatic member function

总结只有方法(成员函数)可以是constvolatile


函数和方法重载的重载标准:

因此,重载一个函数和重载一个方法(成员函数)有不同的标准

函数重载是可能的当且仅当:

  • 参数数量不同。
  • 不同的参数顺序或
  • 不同的论点

While 方法(成员函数)重载是可能的当且仅当:

  • 参数数量不同。
  • 不同的参数顺序或
  • 不同的论据或
  • 不同的cv-qualifer-seq

请注意,返回类型不是重载的条件。因为 C++ 允许实现忽略函数/方法的返回值。


代码示例:

函数重载:

void doSomething(int i);
void doSomething(std::string,int x);

方法重载:

class Myclass
{
     public:
           void doSomething(int i);
           void doSomething(std::string,int x);
           void doSomething(int i) const;
           void doSomething(int i) volatile;
};

以上是一个示例,说明如何将 doSomething() 作为独立函数和方法/成员函数进行重载。

关于c++ - 函数重载和方法重载的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649005/

相关文章:

C++ OO设计: Inheritance of template parameter

python - 如何将类方法分配给类属性?

c++ - 将char数组初始化为字符串值,未初始化的索引是否设置为null?

c++ - 将 'using std::foo' 指令应用于本地构造函数初始化程序列表 (C++)

c - union 内部的 2 个结构,来自头文件

比较两个内存块之间的值是否相等

c - 将 C 函数的返回类型设为 const 有什么用?

ios - 在@IBAction 中分配来自不同类的另一个变量?

c++ - 设计问题 - 多重继承,C++

c++ - Arduino延迟不精确