本文介绍了基本类型的C ++操作符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定义一个运算符,其中一个操作数是定义的类型,另一个是int?
我有一个类 Damage ,并在 Damage.h 中定义:

  #pragma once 

class Damage
{
public:
Damage int = 0,int = 0);

int operator- =(int& num)
{
return num - this-> GetDamage();
}

private:
int damage;
int dotDamage;
int dotDamageLength;
};

我试图在 Monster.cpp

  #includeMonster.h
#includeDamage.h

int Monster :: TakeDamage(伤害和伤害)
{
this->健康 - =伤害; // Error Here
return this-> health;
}

错误是:
No operator - =matches这些操作数。
操作数类型是int - =损伤。



我也尝试使用 - 操作符,在我的许多尝试中,在类外部定义它,传递两个不同的参数,但没有什么工作。

解决方案

这将工作:

  class Damage 
{
public:
Damage ,int b = 0,int c = 0)
:damage(a),dotDamage(b),dotDamageLength(c)
{

}

int GetDamage()const {return damage;}
private:
int损坏;
int dotDamage;
int dotDamageLength;
};
; operator - =(int& n,const Damage& damage)
{
n - = damage.GetDamage();
return n;
}
int operator - (int n,const Damage& damage)
{
return n - damage.GetDamage();
}


How do I define an operator where one operand is a defined type and the other is an int?I have a classDamage and defined as such in Damage.h:

#pragma once

class Damage
{
public:
    Damage(int, int = 0, int = 0);

    int operator-= (int& num)
    {
        return num - this->GetDamage();
    }

private:
    int damage;
    int dotDamage;
    int dotDamageLength;
};

And I am trying to use the operator like this in Monster.cpp:

#include "Monster.h"
#include "Damage.h"

int Monster::TakeDamage(Damage&  damage)
{
    this->health -= damage;        // Error Here
    return this->health;
}

The error is: "No operator "-=" matches these operands. operand types are int -= damage.

I have also tried using the - operator too, among my many attempts, defining it outside the class, passing in two different parameters, but nothing has worked yet.

解决方案

This will work:

class Damage
{
public:
    Damage(int a, int b = 0, int c = 0)
        : damage(a), dotDamage(b), dotDamageLength(c)
    {

    }

    int GetDamage() const { return damage; }
private:
    int damage;
    int dotDamage;
    int dotDamageLength;
};
int& operator -=(int& n, const Damage& damage)
{
    n -= damage.GetDamage();
    return n;
}
int operator -(int n, const Damage& damage)
{
    return n - damage.GetDamage();
}

这篇关于基本类型的C ++操作符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:57