jeudi 31 janvier 2019

Questions on overloading operator+

My code did not work as I expected. For sure, I don't get the operator+ or something else.

the code is as follows:

Vector.h

class Vector
{
public:
    Vector(float x, float y);
    Vector(const Vector& other);
    ~Vector();

    Vector operator+(float a);

private:
    float mX;
    float mY;
};

Vector.cpp

#include "Vector.h"

Vector::Vector(float x, float y) : mX(x), mY(y)
{}

Vector::Vector(const Vector & other) : mX(other.mX), mY(other.mY)
{}

Vector::~Vector()
{}

Vector Vector::operator+(float a)
{
    Vector tmp(0.f, 0.f);
    tmp.mX = a + mX;
    tmp.mY = a + mY;

    return tmp;
}

Main.cpp

#include "Vector.h" 
#include <iostream>


int main()
{
    Vector a(4.5, 2.5);

    Vector b = a + 1.5;
    Vector c = 1.5 + a;   // Compile error


    return 0;
}

Actually, what I want is that both Vector b = a + 1.5 and Vector c = 1.5 + a are working by operator+(float a).

But in the case of Vector c = 1.5 + a, it doesn't work.

I tried to solve it but I didn't. Do I have to add another function? but how??

Sorry to bother you, guys.

Please, enlighten me.

Aucun commentaire:

Enregistrer un commentaire