Das folgende Programm enthält den Fehler
#include <iostream>
namespace _1{
int f(){
std::cout << "_1::f\n";
}
}
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::f\n";
}
}
int main(){
_2::f();
}
Die Diagnose ist
main.cpp: In function ‘int _2::f()’:
main.cpp:13:11: error: ‘int _2::f()’ conflicts with a previous declaration
int f(){
Im Gegensatz dazu ist das folgende Programm korrekt. Der Namespace _1 wird über eine using-Direktive eingeführt.
#include <iostream>
namespace _1{
int f(){
std::cout << "_1::f\n";
}
}
namespace _2{
using namespace _1;
int f(){
std::cout << "_2::f\n";
}
}
int main(){
_2::f();
}
Mit dem erwarteten Ausgang
_2::f
Wie für die gleiche Situation in Block Umfang Sie
#include <iostream>
namespace _1{
int f(){
std::cout << "_1::f\n";
}
}
namespace _2{
int g(){
// As before but in block scope.
using _1::f;
int f();
f();
}
int f(){
std::cout << "_2::f\n";
}
}
int main(){
_2::f();
}
Die Diagnose ist identisch
main.cpp: In function ‘int _2::g()’:
main.cpp:15:15: error: ‘int _2::f()’ conflicts with a previous declaration
int f();
^
Das Parallelkonstrukt das erfolgreiche Probe wäre über
#include <iostream>
namespace _1{
int f(){
std::cout << "_1::f\n";
}
}
namespace _2{
int g(){
using namespace _1;
int f();
f();
}
int f(){
std::cout << "_2::f\n";
}
}
int main(){
_2::g();
}
Mit dem Ausgang
_2::f
Es gibt ein Beispiel, in dem sehr Standardabsatz Sie zitieren. Können Sie näher erläutern, warum Ihnen das nicht beantwortet? – Angew
FYI. C++ 11 fügt einige Beispiele hinzu. Siehe https://timsong-cpp.github.io/cppwp/n3337/namespace.udecl#14. –
Hey! Vergessen Sie nicht, diese Frage zu markieren, wenn die Antworten Ihnen geholfen haben! : D –