我正在嘗試學習C++,目前我正在嘗試瞭解如何在此語言中實現對象組合。C++組成循環依賴項
我有一個Character
類繼承Hero
和Monster
類。
A Character
有一個NormalAbility
和一個SpecialAbility
。
我製作了NormalAbility
和SpecialAbility
類,它們都繼承了一個Ability
超類。
我的問題是,當我在Ability.h中放置#include「Character.h」時,Character.h
中的normalAbility和specialAbility變量不會被識別爲它們的受尊敬的類。錯誤,如 「語法錯誤:標識符串」 顯示德才兼備繼承類的標題
這裏是我的代碼:
Character.h
#pragma once
#include <string>
#include "NormalAbility.h"
#include "SpecialAbility.h"
using namespace std;
class Character
{
public:
Character(string name, string type, int hp, NormalAbility na,
SpecialAbility sa);
bool isDead();
void damage(int amt);
void heal(int amt);
void attack(Character* c, int amt);
private:
string name;
string type;
int hp;
int maxHp;
NormalAbility* normalAblity;
SpecialAbility* specialAbility;
}
Character.cpp
#include "Character.h"
#include <iostream>
Character::Character(string name, string type, int hp, NormalAbility* na,
SpecialAbility* sa)
{
this->name = name;
this->type = type;
this->maxHp = hp;
this->hp = hp;
normalAbility = na;
specialAbility = sa;
}
bool Character::isDead(){
return hp <= 0;
}
void Character::damage(int amt){
if (hp > 0){
hp -= amt;
}
else{
hp = 0;
}
}
void Character::heal(int amt){
if (hp + amt > maxHp){
hp = maxHp;
}
else{
hp += amt;
}
}
void Character::attack(Character* c, int amt){
c->damage(amt);
}
Hero.h
#pragma once
#include "Character.h"
#include <string>
using namespace std;
class Hero :
public Character
{
public:
Hero(string name, int hp);
}
Hero.cpp
#include "Hero.h"
#include <iostream>
Hero::Hero(string name, int hp)
: Character(name, "Hero", hp)
{
}
Ability.h
#pragma once
#include <string>
#include "Character.h"
using namespace std;
class Ability
{
public:
Ability(string name, string type, Character* owner);
void levelUp();
private:
string name;
string type;
int level;
Character* owner;
}
Ability.cpp
#include "Ability.h"
Ability::Ability(string name, string type, Character* owner)
{
this->name = name;
this->type = type;
this->owner = owner;
level = 1;
}
void Ability::levelUp(){
level++;
}
NormalAbility.h
#pragma once
#include "Ability.h"
#include <string>
using namespace std;
class NormalAbility :
public Ability
{
public:
NormalAbility(string name);
}
NormalAbility.cpp
#pragma once
#include "NormalAbility.h"
#include <string>
using namespace std;
NormalAbility::NormalAbility(string name) : Ability(name, "Normal")
{
//some codes
}
什麼是具體症狀? –
「似乎沒有得到承認......」的含義?您無法撥打數據...無法填寫數據......請具體說明。 – Adam
當我在'Ability.h'中放入'#include'Character.h「'時,normalAbility和specialAbility變量不會被識別爲它們的受尊敬的類。錯誤,如「語法錯誤:標識符字符串」顯示在兩個'Ability'繼承類的標題中 – schizoskmrkxx