gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:15:50 26 4
gpt4 key购买 nike

您好,我想了解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com