为什么不添加sqrt()在C ++中引起冲突? [英] Why doesn't adding sqrt() cause a conflict in C++?
问题描述
如果我编写一个具有C库函数签名的新函数,由于模棱两可,我预计会发生编译错误.但是,我不明白为什么下面的C ++代码没有错误.
If I write a new function that has the signature of a C library function, I expect a compile error due to the ambiguity. But, I can't understand why there is no error in the following C++ code.
#include <iostream>
#include <cmath>
using namespace std;
double sqrt(double number)
{
return number * 2;
}
int main( )
{
cout << sqrt(2.3) << endl;
cout << ::sqrt(2.3) << endl;
cout << std::sqrt(2.3) << endl;
return 0;
}
如果我将sqrt()的返回类型更改为int,则由于在cmath中带有双sqrt()的声明含糊性而发生编译错误.如何覆盖double sqrt()?(实际上,所有cmath函数都可以被覆盖,我不知道为什么.)
If I change the return type of sqrt() to int, then a compile error occurs due to the declaration ambiguity with double sqrt() in cmath. How is it possible to override double sqrt()? (Actually, all the cmath functions can be overridden, and I don't know why.)
推荐答案
程序具有未定义的行为.
The program has undefined behaviour.
[保留名称]
1 C ++标准库保留以下类型的名称:
1.1)—宏
1.2)—全局名称
1.3)—具有外部链接的名称
2如果程序在保留它的上下文中声明或定义了一个名称(本条明确允许的情况除外),则其行为未定义.
[reserved.names]
1 The C++ standard library reserves the following kinds of names:
1.1) — macros
1.2) — global names
1.3) — names with external linkage
2 If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.
[外部名称]
4使用外部链接声明的C标准库中的每个函数签名均保留给既可以用作带有extern"C"和extern"C ++"链接的函数签名,也可以用作全局名称空间中名称空间作用域的名称.
[extern.names]
4 Each function signature from the C standard library declared with external linkage is reserved to the
implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a
name of namespace scope in the global namespace.
这篇关于为什么不添加sqrt()在C ++中引起冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!