C++ Operator Overloading with Primitive Types

久未见 提交于 2019-12-11 12:39:49

问题


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.


回答1:


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



回答2:


What you're looking to do is define an operator to convert Damage to an int:

class Damage
{
public:
    // ...
    operator int () const
    {
        return this->GetDamage();
    }
};

Live Demo.

Now that Damage has an implicit conversion to int, you can use it in places where such a conversion is desired. In your case, subtraction:

Damage d; // assume that default damage dealt is 3
int health = 4;
health -= d; // health is now 1


来源:https://stackoverflow.com/questions/34259534/c-operator-overloading-with-primitive-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!