What is the correct way to call one function from another from the same namespace when using the 'using namespace' keyword in the implementation? I get following error:
Call to 'bar' is ambiguous
when compiling this:
// Foo.h
namespace Foo
{
void bar();
void callBar();
}
// Foo.cpp
#include "Foo.h"
using namespace Foo;
void bar() {/* do something */}
void callBar() {bar();}
It appears that you are providing definitions of bar
and callBar
in the cpp file. In this case you should put the functions in the namespace Foo
where they are declared, rather than importing that namespace with using
:
#include "Foo.h"
namespace Foo {
void bar() {/* do something */}
void callBar() {bar();}
}
The using namespace
directive tells the compiler that you want to call functions and refer to classes from the namespace Foo
without qualifying their names explicitly; you can have multiple such directives in your file. It does not tell the compiler that the definitions that you provide below should belong to the namespace Foo
, so the compiler dumps them in the top-level namespace.
The end result is that the compiler sees two bar
s - the Foo::bar()
declared in the Foo
namespace, with external definition, and ::bar()
defined in your cpp file in the default namespace.
You have two bar
s here. one declared in namespace Foo
but not defined and another declared and defined in the global namespace . Both are reachable from the call site because you are using using namespace Foo;
, hence the ambiguity for the compiler.
If the definitions of the functions are for the ones in the Foo
namespace then you should put them in there too.
namespace Foo {
void bar() {/* do something */}
void callBar() {bar();}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.