今日のソース(1時間目)
#include <iostream> #include <string> using namespace std; struct gameChara { string name; //名前 int hp; // 生命力 int mp; // マジックポイント double attack; //攻撃力 }; void setCharStatus(gameChara *_mychar, string _name, int _hp, int _mp, double _atk) { (*_mychar).name = _name; (*_mychar).hp = _hp; (*_mychar).mp = _mp; (*_mychar).attack = _atk; } void printCharStatus(gameChara *_mychar) { cout << "+------------------------" << endl; cout << "+------" << _mychar->name << "-------" << endl; cout << "| HP: " << _mychar->hp << endl; cout << "| MP: " << _mychar->mp << endl; cout << "| AT: " << _mychar->attack << endl; cout << "+-------------------------" << endl; } int main() { //敵enemy_A,enemy_Bと主人公heroを作成 gameChara enemy_A, enemy_B, hero; //enemy_A.name = "青スライム"; //enemy_A.hp = 10; //enemy_A.mp = 0; //enemy_A.attack = 1.2; setCharStatus(&enemy_A, "青スライム", 10, 0, 1.2); // これ作ろう printCharStatus(&enemy_A); }
今日のソース(2時間目)
簡単なクラス(class)を書いてみるよ!
classは構造体(struct)に関数合体したものだよ。
classのメンバは以下のようになります。
- class
- メンバ変数
- メンバ関数
いったん実際に作ってみます!
#include <iostream> #include <string> using namespace std; class cGameChara { private: string name; //メンバ変数:名前 int hp; // メンバ変数:生命力 int mp; // メンバ変数:マジックポイント double attack; //メンバ変数:攻撃力 public: //メンバ変数:キャラクタのステータスをセットする void setStatus(string _name, int _hp, int _mp, double _atk); //メンバ変数:キャラクタのステータスを表示する void printStatus(); void setHP(int _hp); int getHP(); }; //HPのセッター void cGameChara::setHP(int _hp) { this->hp = _hp; } //HPのゲッター int cGameChara::getHP() { return(this->hp); } void cGameChara::setStatus(string _name, int _hp, int _mp, double _atk) { this->name = _name; this->hp = _hp; this->mp = _mp; this->attack = _atk; } void cGameChara::printStatus() { cout << "+------------------------" << endl; cout << "+------" << this->name << "-------" << endl; cout << "| HP: " << this->hp << endl; cout << "| MP: " << this->mp << endl; cout << "| AT: " << this->attack << endl; cout << "+-------------------------" << endl; } int main() { //敵enemy_A,enemy_Bと主人公heroを作成 //gameChara enemy_A, enemy_B, hero; cGameChara mychar[3]; mychar[0].setStatus("青スライム", 10, 0, 1.2); mychar[1].setStatus("ハイパーナイト", 200, 150, 50.0); mychar[2].setStatus("青勇者", 50, 200, 20.5); //privateメンバにはアクセスできない! //mychar[0].mp = 500; for(auto i=0;i<3;i++) mychar[i].printStatus(); }