2013-10-19 70 views
0

我試圖做一小段代碼,它將一起檢查兩個類。它被設定爲大學的工作,但我正在努力使這個最終的功能工作,因爲我也想。將一個類用作另一個類的參數。 (C++)

我不確定主要是如何讓怪物::追逐(類英雄)功能被允許訪問我需要檢查的英雄變量。

我知道這可能是簡單的,我忽視了,或者只是一直盲目,但任何幫助將不勝感激。


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

我很高興你在StackOverflow上找到了你的第一個問題的解決方案。歡迎!請注意'(Hero hero)',創建你的'Hero'對象的*副本*。這可能不是你想要做的。 – Johnsyweb

+0

它似乎已經解決了這個問題,現在進入下一個問題! –

回答

0

你大概意思做這樣的事情:

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

...,你在一個const引用傳遞給的Heroclass一個實例,並調用它hero

你需要更新聲明在頭,太:

void chase(Hero const& hero); 

您可以在hero實例使用.語法然後調用成員函數。

對當前對象(*this)的調用方法可以簡單地按照getX()right()來完成。

相關問題