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.
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.
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.
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.
7. Which function overloads the >> operator? Explanation: __rshift__() overloads the >> operator.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With