首页 > 解决方案 > 如何做多个运算符重载函数?

问题描述

我尝试测试一些重载运算符,但是当我尝试执行多个组合时,它不会执行第二个。它不添加第二个兰特值。我该如何解决这个问题?我尝试添加不同的重载,但它保持不变。多桩+重载。我对其他运营商也有同样的问题。

主功能

// 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
{
 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);

函数声明

 #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());
}

标签: c++operator-overloading

解决方案


推荐阅读