c ++类函数里面调用另一个类函数

时间:2015-11-14 18:49:10

标签: c++ function class

我目前正在使用c ++和sfml 2.3进行我的塔防游戏,有3个班级

我的主要cpp文件中的代码片段

问题:当在tower.h类中调用RangeCollision()时,我想将一些变量发送到不同的类(mobs类)来运行ReduceMinionHealth并让它降低minions的健康状况

    #include <Defines.h> //defining bunch of includes and defines

    #include "Mobs.h"
    #include "Towers.h"
    #include "MainClass.h"
    int main() {
    MainClass* mainObj = new MainClass();
    TowerClass* towerObj = new TowerClass();
    MobsClass* mobsObj = new MobsClass();
    //keeps checking for actions and detecting clicks
    towerObj->BulletCollision(mobsObj->Mob1v, speedMultiplier); //detects when bullet reached minion
    if (mainObj->waveStarted) mobsObj->MobPathing(speedMultiplier); //minions moving their path
    //drawing sprites
    return(0);
    }

MainClass.h文件

#ifndef MainClass_h
#define MainClass_h

#include "Defines.h"

class MainClass {
    static int map[];
public:
    static int coins, lives;
    static bool waveStarted;

    MainClass::MainClass() {
        //constructor loading some stuff
    }
//bunch of functions

};

tower.h类文件

#ifndef Towers_h
#define Towers_h

#include <Defines.h>
#include "MainClass.h"

class TowerClass: public MainClass {
private:
    vector<int> towerDmg;
    vector<int> towerCost;
    vector<float> towerRange;
public:
    bool Clicked;
    float dx, dy, magnitude;
    //loading textures and other variables

typedef struct {
    //sprites, tower params
    vector<Sprite> bullet;
    vector<int> shootAt;
}towerParamStruct;

vector<towerParamStruct> TowerParam;

TowerClass::TowerClass() {
//constructor
}

void BulletCollision(vector<Sprite> &Mob1v, float speedMultiplier) {
     //doing some stuff and at some point calling 
     MobsClass::MinionHealthReduce(int i, double DamageDealt) //gives me error
}
};

下面的mobs.h课程

#ifndef Mobs_h
#define Mobs_h

#include "Defines.h"
#include "MainClass.h"

class MobsClass: public MainClass {
    private:
        vector<double> *Health, *levelHealth;
        vector<int> *levelMobsCount, *levelCoins;
    public:
    Sprite Mob1;
    vector<Sprite> Mob1v;

    MobsClass::MobsClass() {
    //constructor which prepares for first wave
    }

    void MinionHealthReduce(int i, double DamageDealt) {
        if (Health->at(i) > 0) {
            //recalculating hp bar
            Health->at(i) = Health->at(i) - DamageDealt;
        }
        if (Health->at(i) <= 0) {
            //add coins because u killed minion
            //destroys minion
        }
    }
};

1 个答案:

答案 0 :(得分:0)

我相信我看到了你的错误,如下所示:

MobsClass::MinionHealthReduce(int i, double DamageDealt)

我可以看到3个错误:

  1. 没有分号

  2. 需要使用对象调用

  3. 无法使用(int i, double DamageDealt)

  4. 进行调用

    修正版:

    MobsClass* mobsObj = new MobsClass();
    mobsObj.MinionHealthReduce(i, DamageDealt);
    

    我相信这可以解决你的问题,但我不确定究竟是什么问题。 如果它是关于传递变量的东西,请记住通过引用传递它们。

    编辑:我正试图了解Zehryo Karham在评论中所说的内容。我刚读了这些评论。