引用 using 声明引入的功能的句子是什么意思?

What is the meaning of the sentence referring to functions introduced by a using declaration?

本文关键字:句子 是什么 意思 功能 引用 声明 using      更新时间:2023-10-16

我正在学习C++03标准,现在正在阅读[7.3.3]/11,但我无法理解以下段落:

如果命名空间作用域或块作用域中的函数声明具有相同的名称和相同的参数 类型为由 using-声明引入的函数,并且声明不声明相同的函数, 程序格式不正确。

我在任何地方都没有找到任何这种情况的例子,我不明白这段话的意思。

意思是:

namespace namespace_1
{
void foo(int number);
}
using namespace_1::foo;
void foo(int roll_no);

这意味着程序格式不正确。 我相信这意味着说该函数阅读起来会令人困惑。在某一时刻,函数定义将使用传递的 int 作为整数(常规(,但在另一种情况下,我们将它用作roll_no。

这也会导致重载函数匹配的歧义。

您引用的来源在您引用的行下方给出了一个例子:

namespace B {
void f(int);
void f(double);
}
namespace C {
void f(int);
void f(double);
void f(char);
}
void h() {
using B::f;       // B::f(int) and B::f(double)
using C::f;       // C::f(int), C::f(double), and C::f(char)
f('h');           // calls C::f(char)
f(1);             // error: ambiguous: B::f(int) or C::f(int)?
void f(int);      // error: f(int) conflicts with C::f(int) and B::f(int)
}

以下程序包含错误

#include <iostream>
namespace _1{
int f(){
std::cout << "_1::fn";
}
}
namespace _2{
/*
*If a function declaration in namespace scope or block scope has the 
*same name and the same parameter types as a function introduced by
* a using-declaration
*/
using _1::f;
// This is not the same function as introduced by the using directive
int f(){
std::cout << "_2::fn";
}
}
int main(){
_2::f();
}

诊断为

main.cpp: In function ‘int _2::f()’:
main.cpp:13:11: error: ‘int _2::f()’ conflicts with a previous declaration
int f(){

作为对比,以下程序是正确的。_1 命名空间是通过 using 指令引入的。

#include <iostream>
namespace _1{
int f(){
std::cout << "_1::fn";
}
}
namespace _2{
using namespace _1;
int f(){
std::cout << "_2::fn";
}
}
int main(){
_2::f();
}

具有预期的输出

_2::f

至于块范围内的相同情况,您有

#include <iostream>
namespace _1{
int f(){
std::cout << "_1::fn";
}
}
namespace _2{
int g(){
// As before but in block scope.
using _1::f;
int f();
f();
}
int f(){
std::cout << "_2::fn";        
}
}
int main(){
_2::f();
}

诊断结果相同

main.cpp: In function ‘int _2::g()’:
main.cpp:15:15: error: ‘int _2::f()’ conflicts with a previous declaration
int f();
^

上面成功示例的并行构造将是

#include <iostream>
namespace _1{
int f(){
std::cout << "_1::fn";
}
}
namespace _2{
int g(){
using namespace _1;
int f();
f();
}
int f(){
std::cout << "_2::fn";        
}
}
int main(){
_2::g();
}

带输出

_2::f