0

我正在尝试制作一小段代码,它将一起检查两个类。它被设置为大学工作,但我正在努力使这个最终功能也能按我的意愿工作。

我不确定如何让 Monster::chase(class Hero) 函数也被允许访问我需要检查的 Hero 变量。

我知道这可能是我忽略了一些简单的事情,或者也只是盲目,但任何帮助将不胜感激。


//Monster.cpp

#include "Creature.h"
#include "Monster.h"
#include "Hero.h"

Monster::Monster() : Creature(m_name, m_xpos, m_ypos)
{
}

void Monster::chase(class Hero)
{
    if(Monster::m_xpos < Hero::m_xpos) //Error: a nonstatic member reference must be relative to a specific object
    {
        Monster::right();
    }

    if(Monster::m_xpos > ___?___)
    {
        Creature::left();
    }

    if(Monster::m_ypos < ___?___)
    {
        Creature::down();
    }

    if(Monster::m_ypos >___?___)
    {
        Creature::up();
    }
}

bool Monster::eaten(class Hero)
{

    if((Monster::m_xpos == ___?___)&&(Monster::m_ypos == ___?___))
    {
        return true;
    }
}

//monster.h

#pragma once
#include "Creature.h"

class Monster : public Creature
{
public:
    Monster();
    void chase(class Hero);
    bool eaten(class Hero);
};

#include "Creature.h"

Creature::Creature(string name, int xpos, int ypos)
{
    m_xpos = xpos;
    m_ypos = ypos;
    m_name = name;
}

void Creature::Display(void)
{
    cout << m_name << endl;
    cout << m_xpos << endl;
    cout << m_ypos << endl;
}

void Creature::left(void)
{
    m_xpos = m_xpos+1;
}

void Creature::right(void)
{
    m_xpos = m_xpos-1;
}

void Creature::up(void)
{
    m_ypos = m_ypos-1;
}

void Creature::down(void)
{
    m_ypos = m_ypos+1;
}

void Creature::setX(int x)
{
    m_xpos = x;
}

void Creature::setY(int y)
{
    m_ypos = y;
}

int Creature::getX(void)
{
    return m_xpos;
}

int Creature::getY(void)
{
    return m_ypos;
}


最终使用它作为解决方案!

感谢所有建议答案的人!

多么棒的社区!

void Monster::chase(Hero hero)
{
    if(getX() < hero.getX())
    {
        right();
    }
4

1 回答 1

0

您可能打算执行以下操作:

void Monster::chase(Hero const& hero)
{
    if (getX() < hero.getX())
    {
        right();
    }
// [...]

...您将 const-reference 传递给 the 的实例Hero class并调用它hero

您还需要更新标头中的声明

 void chase(Hero const& hero);

然后,您可以使用语法在hero实例上调用成员函数。.

调用当前对象 ( *this) 的方法可以像getX()和一样简单right()

于 2013-10-19T05:23:37.657 回答