【问题标题】:Overloading output operator is not working as intended重载输出运算符未按预期工作
【发布时间】:2022-01-03 08:39:44
【问题描述】:

我正在尝试重载 std::cout << player2; 我得到“0x7f60b0100”作为输出。

“player2”是一个 Actor*,所以我不确定发生了什么。

class Actor {

private:
    string type;
protected:
    int health;
    int damage;
    vector<MoveType> moves;

public:
    Actor(string type, int health): type{ type }, health{ health }{damage=0;}
    virtual void Hit(int damage){health = health-damage;}
    virtual void Heal(int amount){health=+amount;}
    const vector<MoveType>& GetMoves() const {return moves;}

    bool IsDead() { return health <= 0; }

    friend ostream& operator<<(ostream& out, const Actor& actor){
        return (out << "DAMAGE DONE: " << actor.damage << "HEALTH: "<< actor.health);
    }
};

【问题讨论】:

    标签: c++11


    【解决方案1】:

    正如你所说,它是一个指向 Actor 实例的指针,所以这就是你打印出来的,这个指针的值。

    你需要取消引用指针:

    std::cout << *player2;
    

    【讨论】:

    • 谢谢!取消引用指针非常有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2022-12-18
    • 2015-05-11
    • 2019-06-20
    相关资源
    最近更新 更多