vendredi 24 juillet 2020

C++ Using overloaded << to output an overloaded unary + / - operator

As part of an exercise, I have to overload operators on a class Vector3D.

I have overloaded most of the operators but I am stuck on the last part, where I have to overload the unary operator -, and output the results with the << that I have already overloaded.

I have tried looking for solutions online but none of them seem to be the answer I am looking for. Please guide me through this!

Below are parts of code that are relevant:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <fstream>
#include <istream>

class Vector3D {
private:
    double x, y, z;

public:
    Vector3D() { x = 0, y = 0, z = 0; }
    Vector3D(double, double, double);
    friend std::ostream& operator<<(std::ostream& output, Vector3D& a);
//Unary operator overloading
    Vector3D operator-();
};

std::ostream& operator<<(std::ostream& output, Vector3D& a)
{
    output << "(" << a.x << "," << a.y << "," << a.z << ")" << std::endl;
    return output;
}

Vector3D Vector3D::operator-()
{
    Vector3D output;
    output.x = -this->x;
    output.y = -this->y;
    output.z = -this->z;
    return output;
}

int main()
{
    Vector3D unary_Positive(1, 3, 3);
    std::cout << unary_Positive << std::endl; //This works
    std::cout << -unary_Positive << std::endl; //This gives an error
    return 0;
}

Running this code gives me errors:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0349   no operator "<<" matches these operands 

and

Severity    Code    Description Project File    Line    Suppression State
Error   C2679   binary '<<': no operator found which takes a right-hand operand of type 'Vector3D' (or there is no acceptable conversion)   

I was able to work around the problem by creating a temporary Vector3D object, and copying

-unary_Positive

to it, and then using the operator << to print it.

Aucun commentaire:

Enregistrer un commentaire