【问题标题】:Using a class as a parameter with another class. (C++)使用一个类作为另一个类的参数。 (C++)
【发布时间】:2013-10-19 05:08:05
【问题描述】:

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

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

【问题讨论】:

  • 很高兴您在 StackOverflow 上找到了第一个问题的解决方案。欢迎!请注意,(Hero hero) 创建了您的Hero 对象的副本。这可能不是您想要做的。
  • 似乎已经解决了一些问题,现在进入下一个问题!

标签: c++ function inheritance


【解决方案1】:

你可能打算这样做:

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

...您将常量引用传递给Hero class 的实例并将其命名为hero

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

 void chase(Hero const& hero);

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

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

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多