Marco T. wrote:
Hi all,
why the former code fragment works and the latter doesn't?
=============
//CORRECT CODE:
namespace ciao
{
class A{};
A operator *(A &a, A &b) {return a;};
A method() ;
You never implement method().
}
using namespace ciao;
A method() {A a1,a2; return a1*a2;}
This function is new - it is not an implementation of ciao::method.
=============
//INCORRECT CODE
namespace ciao
{
class A{};
A operator *(A &a, A &b);
A method() ;
You never implement operator * and method.
}
using namespace ciao;
A operator *(A &a, A &b) {return a;}
A method() {A a1,a2; return a1*a2;} //line X
error: 'operator *' is ambiguous at line X
The compiler does not know if it should call ::operator *(A &a, A &b)
or ciao::operator *(A &a, A &b). Both are "perfect" fits and would be
so even without the using directive.
(compiler: VC++ 6.0)
Its to old (and has been for lots of years!). Get a new one from
Microsoft or gcc. Both are nice and free.
>
=============
The issue is that I don't want to write the implementation of operator
* inside the namespace declaration.
The problem is that you don't understand using directives. The using
namespace ciao directive in your first example only tells the compiler
to look up names in that namespace. The method you declare will be in
the global namespace. To declare the method in the ciao namespace you
must write it "inside" the namespace. E.g.:
A ciao:method() {A a1,a2; return a1*a2;}
-or-
namespace ciao // reopening the namespace
{
A method() {A a1,a2; return a1*a2;}
}
(If the function was more complex, it would normally be placed in a
..cpp file).
So every function must be defined (implemented) in the same namespace
as its declartation.
/Peter