I am making a three-dimensional vector class (called Vector3) in c++. Right now, I am trying to overload the stream insertion operator (<<) so that I can directly print all of the vector’s components all at once. I copied the sintax from MSD, but I get an 3 errors.
error: passing ‘const Vector3 ‘ as ‘this’ argument of ‘float Vector3::getX()‘ discards qualifiers [-fpermissive]
error: passing ‘const Vector3 ‘ as ‘this’ argument of ‘float Vector3::getY()‘ discards qualifiers [-fpermissive]
error: passing ‘const Vector3 ‘ as ‘this’ argument of ‘float Vector3::getZ()’ discards qualifiers [-fpermissive]
(differences are marked in bold)
In Vector3.h under public, I entered this function declaration:
friend ostream& operator<<(ostream &os, const Vector3 &vector);
In Vector3.cpp, I implemented it:
ostream& operator<<(ostream& os, const Vector3& vector)
{
os << "(" << vector.getX() << ", " << vector.getY() << ", " << vector.getZ() << ")" << endl;
return os;
}
It should print out something like (x, y, z) according to the x, y, and z variables.
On a side note, shouldn’t the vector.getX() lines use the -> instead of the dot, because the vector object is an address pointer?
Add
constqualifiers to yourget...functions.A
const-qualified function simply means you can call it on aconstinstance of the class. Here, the getters won’t change anything. However, if you don’t specify that, the compiler doesn’t know, so calling a function that might change something on aconstvariable is not allowed.You can read about
const-correctness here.And the dot notation is correct,
vectoris not a pointer, but a reference (i.e. another name for some otherVector3. The¬ation can be a little confusing for beginners I think. Roughly: when you apply it to a variable, it takes its address, when it’s part of a type, it means that type is a reference. E.g. see here or here.