【发布时间】:2018-04-01 22:04:10
【问题描述】:
所以这里的问题是玩家需要一张卡片,因此,卡片需要在 Player 类之上声明。在我的 Card 类上进一步使用需要 Player 指针参数的函数。为了消除其他错误,我在 Card 类上方使用了前向声明来使 Player 类可见。我还在 attackEnemy 函数参数中使用了指向 Player 的指针,因为此时仅通过前向声明无法知道对象的大小。当我尝试从卡内的 attackEnemy 函数中传递的 Player 指针调用函数时,出现编译错误。错误是error C2227: left of '->looseHealth' must point to class/struct/union/generic type。
这是程序:
#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;
}
【问题讨论】:
-
编译器在您使用它时不知道
looseHealth是什么。该函数稍后在您的源模块中定义。是时候学习如何制作单独的.cpp和.h文件,并将函数体移出类定义。 -
编译器需要已经看到
class Player的完整定义。
标签: c++ pointers compiler-errors dependencies forward-declaration