使用类作为另一个类的参数。 (C ++)

时间:2013-10-19 05:08:05

标签: c++ function inheritance

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

我不确定如何让Monster :: chase(类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();
    }

1 个答案:

答案 0 :(得分:0)

您可能打算做以下事情:

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

...将const引用传递给Hero class的实例,并将其称为hero

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

 void chase(Hero const& hero);

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

调用当前对象(*this)上的方法可以像getX()right()一样完成。