クラスでやりたいことを書く、メインでこのクラスのこの関数を実行する。この時はこのクラスのこの関数、あの時はこのクラスのこの関数といった具合にまるでYES/NOチャートのように
書くことができるので、プログラミングの楽しさを取り戻しました。
カプセル化・承継・多態性などを学ぶ前に
これをC++に置き換えて学習すればわかりやすくC++をマスターできるのではないかと学習にとりかかりましたが
これはC言語ではできるのかできないのかがわからず学習がストップしてしまいました。
問題はhas-a関係の箇所で
Hero.h
#include "main.h"
class Hero{
public:
static int money;
Hero();
Hero(string name);
string name;
int hp;
Sword sword;
int sleep();
void sit(int sec);
void slip();
void rum();
};
#include "Hero.h"
Hero::Hero(){
}
Hero::Hero(string name){
Hero::hp = 50;
Hero::name = name;
cout << Hero::name << "名前入力完了!コンストラクタが呼び出されました" << endl;
}
int Hero::sleep(){
cout << Hero::name << "は、眠って回復した" << endl;
return 0;
}
void Hero::sit(int sec){
Hero::hp += sec;
cout << Hero::name << "は" << sec << "秒座った" << endl;
cout << "HPが" << sec << "ポイント回復した。現在HP=" << hp << endl;
}
void Hero::slip(){
Hero::hp -= 5;
cout << Hero::name << "は転んだ" << endl;
cout << "5のダメージ" << endl;
}
void Hero::rum(){
cout << Hero::name << "は逃げ出した" << endl;
cout << "GAME OVER" << endl;
cout << "最終HPは" << Hero::hp << "でした" << endl;
}
#include "main.h"
#pragma once
class Sword
{
public:
Sword(string name);
Sword();
~Sword();
string name;
int damage;
void Test(Hero x);
};
#include "Sword.h"
Sword::Sword(string name)
{
damage = 0;
cout << name << "の剣を手に入れた" << endl;
}
Sword::~Sword()
{
}
void Sword::Test(Hero x){
x.hp += 10;//ここもほかのクラスの変数を引数に渡すとエラーに・・・
#include "main.h"
#include "Hero.h"
#include "Matango.h"
#include "Cleric.h"
#include "Sword.h"
#include "Wizard.h"
int Hero::money = 0;
void main(){
cout << "こんにちは" << endl;
srand((unsigned int)time(NULL));
int T = rand() % 2;
cout << T << endl;
cout << "所持金" << Hero::money << endl;
Hero *r = new Hero();
Hero x("たかはし");
Hero* h = new Hero("うんこまん");
Cleric c("パウエル");
Sword *s = new Sword("ほのお");
Wizard *w;
//x.sword = s; 問題の箇所
Matango m1;
m1.hp = 50;
m1.suffix = 'A';
Matango m2;
m2.hp = 48;
m2.suffix = 'B';
c.selfAid();
c.pray(T);
h->sleep();
h->sit(5);
m1.run();
m2.run();
h->sit(T);
h->rum();
x.rum();
x.Hero::money +=500;
cout << "所持金" << Hero::money << endl;
h->Hero::money += 10;
cout << "所持金" << Hero::money << endl;
delete s, r;
}
ほかにもHeroのクラスないでSwordをインスタンス化してもエラーになってしまいます。
Swordのクラス内でHeroのクラスの変数を引数にしたり、変更したりなどはできないのでしょうか?
よろしくお願いいたします。