クラスの配列を作成して印刷したいと思います。C++クラスの配列を作成して印刷する
今の私のアプローチは、次のとおりです。
- その配列を印刷する機能を使用して、これらのクラスの1
- の配列を作成する機能を使用
- 使用集約
- に2つの異なるクラスを作成します。
- すべての関数は型voidでなければなりません。
#include <iostream>
#include <string>
using namespace std;
const int invsize = 5;
//first class:
class Item {
private:
//i'm supposed to have all values set to private
string itname;
int itpower;
int itlasting;
public:
//this is so I can create an array of those classes later:
Item(string i, int j, int k) { itname = i; itpower = j; itlasting = k; }
//a method to print this class:
void itprint() {cout << itname << itpower << itlasting;};
~Item(){};
};
//second class:
class Player {
private:
string plname;
int plrole;
int plbrain;
int plbrawn;
//aggregation:
Item * Inventory;
public:
void plprint();
Player();
~Player();
};
//a Player constructor, in which I want to create the array of "Items" also:
Player::Player() {
/*I'm adding info to the Player class first, it works fine and is irrelevant to my question so I didn't paste it here*/
//now I'm creating an array of Item classes and giving them values:
Item Inventory[4] = { Item("generic name", 5, 5), Item("generic name", 5, 5),
Item("generic name", 5, 5), Item("generic name", 5, 5) };
}
//a method to print the Player class and the "Inventory" array:
void Player::plprint() {
/*printing the info about the Player class here first, again, works fine and is irrelevant so I didn't copypaste it*/
//printing the "Inventory" array:
cout << "Your inventory contains:" << endl;
for (int i=1;i<invsize;i++) {
Inventory[i].itprint();
}
}
//and finally the main:
int main() {
//creating a Player class - as I understand, the "Inventory" array should get created with it
Player * firstPlayer = new Player;
//printing the created object and its inventory
firstPlayer->plprint();
system("pause");
return 0;
}
プログラムをコンパイルし、私はそれを実行すると、正しくプレイヤークラスを作成しているようだ、それもうまくプレーヤーに関する情報を印刷し、その後、何かがうまくいかない:は、ここで私がこれまで持っているものですアレイとすべてのものがクラッシュする。
私はここで何かを理解できないと確信しています。私はどんな種類の助けにも非常に感謝しています。私はたくさんのグーグルで探せましたが、関連するチュートリアルや質問に答えられませんでした。前もって感謝します!また、私の悪い英語を言い訳、それは私の第二言語です。
、このような問題を解決するための適切なツールは、あなたのデバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –
デバッガを使用してコード内のすべての行をステップ実行して問題を特定し、問題の原因となっている行またはコードブロックを投稿してみません。これにより、私たちがあなたを助けやすくなります。 –
'Itemクラスの配列を作成し、値を与えています:'作成している配列はローカルです。これは 'Player'コンストラクタが返っても存在しなくなりました。 – PaulMcKenzie