0

I Try to test some overloading operators but when i try to do multiple combined it doest do the second one. it Dont add the second rand value. How can i solve this? I tried to add different overloads but it stays the same. Multpile + overloads. I Have also the same problem with the other operators.

main function

// Initialize
int healthValue{ 0 };
Health healthObject{ healthValue };
int randValue{};
int testCntr{};


// Checking return is Health&
int randValue1 = rand() % 5 + 1; //[1,5]
int randValue2 = rand() % 5 + 6; // [6,10]
(healthObject += randValue1) += randValue2;
(healthValue += randValue1) += randValue2;
assert(healthObject.GetValue() == healthValue);
std::cout << "ok\n";

class health

class Health
{
 public:
Health(int value);
int GetValue() const;


Health operator+=(const int rhs);
Health operator-=(const int rhs);

//friend Health operator+(const Health& lhs, const int rhs);
//friend Health operator-(const Health& lhs, const int rhs);

//friend Health operator+(const  int lhs, const Health rhs);
//friend Health operator-(const  int lhs, const Health rhs);


private:
int m_Value;
};

Health operator+(const Health& lhs,  int rhs);
Health operator-(const Health& lhs,  int rhs);
Health operator+( int lhs, const Health rhs);
Health operator-( int lhs, const Health rhs);



//friend Health operator+(const Health& lhs, const int rhs);
//friend Health operator-(const Health& lhs, const int rhs);

//friend Health operator+(const  int lhs, const Health rhs);
//friend Health operator-(const  int lhs, const Health rhs);


private:
int m_Value;
};

Health operator+(const Health& lhs,  int rhs);
Health operator-(const Health& lhs,  int rhs);
Health operator+( int lhs, const Health rhs);
Health operator-( int lhs, const Health rhs);

Function declarion

 #include "pch.h"
 #include "Health.h"
 #include <iostream>

 Health::Health(int value)
: m_Value{ value }
{
}
int Health::GetValue() const
{
return m_Value;
}

Health Health::operator+=(int rhs) {
this->m_Value = this->m_Value + rhs;
std::cout << this->m_Value + rhs << "\n";
return *this;
}

Health Health::operator-=(int rhs) {
this->m_Value -= rhs;

return *this;
}

Health operator+( Health& lhs, const int rhs) {
lhs += rhs;
return lhs;
}
Health operator-(const Health& lhs, const int rhs) {
return Health(lhs.GetValue() - rhs);
}


Health operator+(const int lhs,  Health& rhs) {
rhs += lhs;
return rhs;
}


Health operator-(const int lhs, const Health& rhs) {
return Health(lhs - rhs.GetValue());
}
  • `Health operator+=(const int rhs);` has the wrong return type it should return a reference to `*this`. Compound operators are not supposed to create a new instance. The operator is called, just not on the object you expect it – 463035818_is_not_an_ai Feb 10 '21 at 14:09
  • The compound assignment operators usually return a reference to `*this`, not a copy. (And the non-assignment operators, such as `+`, should not modify their operands.) – molbdnilo Feb 10 '21 at 14:10

0 Answers0