Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace + overloaded std::ostream << operator

I'm trying to make a Vector3D class in my c++ application. For my entire program, I'm using a namespace. In this namespace I've declared my Vector3D class and an overloaded operator<< for it as such:

namespace space
{
    class Vector3D
    {
      public:
        float x, y, z;

        Vector3D(float _x = 0, float _y = 0, float _z = 0);
        Vector3D(const Vector3D & _vector);

        Vector3D & operator=(const Vector3D & _vector);
        Vector3D operator*(float _scalar);
        Vector3D operator*(const Vector3D & _vector); //CROSS PRODUCT

        float magnitude() const;
        float magnitude2() const; //FOR SPEED
        Vector3D normalize() const;
    };

    std::ostream & operator<<(std::ostream &, const Vector3D &);
}

It compiles just fine too. My problem is to cout a Vector3D, I have to manually call

space::operator<<(cout, vector);

which is a pain. I'd like to try to avoid "using namespace space;", because I like the prefix on all the rest of the objects in "namespace space".

My final question: Is there any way to call an overloaded operator function inside a namespace without using that namespace?

Thanks for the help.

like image 304
lowq Avatar asked Oct 07 '11 22:10

lowq


People also ask

Can we overload << operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.

What is ostream operator?

A function that takes and returns a stream object. It generally is a manipulator function. The standard manipulators which have an effect when used on standard ostream objects are: manipulator.

How do you overload left shift operator?

you can't overload left shift operator like this in c#. Because in the left shift operator, the first operand must be the containing type and second operand must be an integer.

Which function overload the >> operators?

7. Which function overloads the >> operator? Explanation: __rshift__() overloads the >> operator.


1 Answers

My problem is to cout a Vector3D, I have to manually call space::operator<<(cout, vector);

You don't, that's what ADL (Argument-dependent name lookup, also known as Koenig's lookup) is about. It should be enough to do

cout << vector;

If it doesn't work, either you are working with an ancient compiler or you are doing something else wrong.

like image 120
K-ballo Avatar answered Sep 24 '22 16:09

K-ballo