C ++错误C2227:' - > looseHealth'必须指向class / struct / union / generic类型

时间:2018-04-01 14:01:02

标签: c++ pointers compiler-errors dependencies forward-declaration

所以这里的问题是玩家需要一张卡,因此需要在玩家类之上声明卡。我的Card类继续使用需要Player指针参数的函数。为了删除其他错误,我使用Card类上方的前向声明来使Player类可见。我还在attackEnemy函数参数中使用指向播放器的指针,因为只有前向声明才能知道对象的大小。当我尝试从卡内的attackEnemy函数中传递的Player指针调用一个函数时,我得到一个编译错误。错误是错误C2227:左边的' - > looseHealth'必须指向class / struct / union / generic类型

这是该计划:

#include "stdafx.h"
#include <iostream>
using namespace std;
class Player;
class Card {
private:
    int attack;
public:
    Card() {
        this->attack = 2;
    }

    void attackEnemy(Player* i) {
        i->looseHealth(this->attack); //error is here
    }
};

class Player {
private:
    string name;
    int health;
    Card* playersCard;
public:
    Player(string name) {
        playersCard = new Card();
        this->name = name;
    }

    void looseHealth(int x) {
        cout << "lost health -" << x << " points" << endl;
        health -= x;
    }
};

int main()
{
    Card* opponedsCard = new Card();
    Player* player1 = new Player("player 1");
    opponedsCard->attackEnemy(player1);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

attackEnemy使用的是不完整类型Player,它是向前声明的。

只需在void attackEnemy(Player* i);课程中声明Card即可 移动

void attackEnemy(Player* i) {
        i->looseHealth(this->attack); //error is here
    }

定义Player

之后
void Card::attackEnemy(Player* i) {
        i->looseHealth(this->attack); //error is here
    }
相关问题