简体   繁体   English

在C ++中定义具有相同签名的两个函数

[英]Define two functions with the same signature in C++

Why can we define two functions with the same signature in the following way? 为什么我们可以通过以下方式定义具有相同签名的两个函数?

extern void print(int *ia, int sz);
void print(int *array, int size);

Those are not definitions, they are (redundant) declarations . 这些不是定义,它们是(冗余) 声明 If you would turn them both into definitions by providing a function body, you would certainly get an error from your compiler. 如果通过提供一个函数体将它们都变成定义,那么您肯定会从编译器中得到一个错误。

"Declaration" in C and C++ just tell the name, and type of that name. 在C和C ++中,“声明”仅说明名称和名称类型。

"Definition" in C and C++ actually brings things into existence. C和C ++中的“定义”实际上使事物存在。 Space for a variable gets allocated and the initial value set, a function code gets generated etc (ok, this is a bit simplified version). 为变量分配空间,并设置初始值,生成功能代码等(好的,这是简化的版本)。

Those two are declarations , because they lack function body. 这两个是声明 ,因为它们缺少函数体。 And since they are functions, extern is unnecessary so they are equal. 并且由于它们是函数,因此extern是不必要的,因此它们是相等的。 You can declare same thing as many times as you want, as long as there's not conflict. 只要没有冲突,您可以多次声明同一件事。 And since functions allow overloading based on parameters in C++, you can only get conflict if you make functions which have same parameters but different return type. 并且由于函数允许基于C ++中的参数进行重载,因此,如果您使函数具有相同的参数但返回类型不同,则只会产生冲突。 With variables or C functions you can't have name clashes. 使用变量或C函数时,不能有名称冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM