c++ - 如何做多个运算符重载函数?
问题描述
我尝试测试一些重载运算符,但是当我尝试执行多个组合时,它不会执行第二个。它不添加第二个兰特值。我该如何解决这个问题?我尝试添加不同的重载,但它保持不变。多桩+重载。我对其他运营商也有同样的问题。
主功能
// 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());
}
解决方案
推荐阅读
- perl - 在 Perl 中使用 'gradlew' 挂断
- typescript - 使用函数重载进行解构
- javascript - 如何从 iframe 中删除滚动条并仍然在其中滚动?
- java - 我的java项目中的gradle依赖关系如何映射
- c - 在 C 中管道标准输出
- php - RedbeanPHP 多对多关系 - 奇怪的行为
- javascript - JS:遍历div列表以通过onclick添加事件?
- php - 从非静态的多维数组中获取页面 id
- php - 如何正确使用 AngularJS $http.post 通过 PHP 更新 MySQLi 表?
- ios - 沿着 BezierPath 移动 UILabel 一段时间