このプログラムは最近C++を勉強して私が作りました。
それで本とか色々読んでいて気づいた事があるんですが、
このstringはname[10]とHumanクラスで宣言してしまっていますが、
この方法は合っているんでしょうか?
例えば、もし2000人分のnameを保存したくて、string name[2000]と
書いてしまうと、PCがフリーズしてしまいませんか?
このやり方がだめなら、もしよければ、良い方法を教えていただけますか?
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
// Human class
class Human{
string name[10];
public:
Human(){};
void Input();
void Display();
};
void Human::Input(){
string InS;
for ( int i = 0 ; i < 2 ; i++){
cout << "Please enter Humans' name." << endl;
cin >> InS;
cout << endl;
name[i] = InS;
}
}
void Human::Display(){
for ( int j = 0 ; j < 2 ; j++){
cout << name[j] << endl;
}
}
int main(){
Human *p;
p = new Human();
p -> Input();
p -> Display();
delete p;
return 0;
}
>string name[10];
1つの Human につき10個名前があるのですか?
>例えば、もし2000人分のnameを保存したくて
Human *p = new Human[2000];
↑で、2000人分のメモリを確保できます。
心配ならば、new の例外処理で、メモリの確保に失敗した時の処理を正しく記述すれば問題ないでしょう。
趣味のプログラムであれば、省略してもいいんじゃないでしょうか?
返事ありがとうございます。
えーと、それはどのあたりに入れたらよろしいですか?
mainの中ですか?
int main(){
Human *p;
p = new Human(); // <== の処理に対して記述
p -> Input();
p -> Display();
delete p;
return 0;
}
えーと
Human *p;
Human *p = new Human[2000];
こうですか?
でもエラーが出ますが^−^;;
エラーが出るときはどんなエラーが出るのか書きましょう。
そもそもクラスの作りがとんでもないと思うのは私だけ?^^;
Humanクラスの中に人数の要素がnameの配列数の形で入ってるとは。。。
自分ならこうします。
#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>
class Human{
std::string name;
public:
Human(){};
void Input();
void Display();
};
void Human::Input(){
std::cout << "Please enter Humans' name." << std::endl;
std::cin >> name;
std::cout << std::endl;
}
void Human::Display(){
std::cout << name << std::endl;
}
int main(){
int num=0;//人数
std::cout << "Please enter the number of people. " << std::endl;
std::cin >> num;
std::cout << std::endl;
std::vector<Human> people;
Human t;
for(int i=0;i<num;i++)
{
t.Input();
people.push_back(t);
}
for(i=0;i<num;i++)
people[i].Display();
return 0;
}
もしできたら例外処理の仕方を教えていただけますか?
キーワードは try と catch です。調べてみましょう。
fooさんありがとうございます。
後できたら
std::vector<Human> people;
の処理の説明お願いできますか?
C++の標準テンプレートライブラリのvectorというコンテナです。
配列と同じような"感じ"に扱えますが、
大きさが可変で、newやdeleteに気を配らなくていいのが楽。
簡単に解説すると
vector<int> hoge;
とするとint型のvectorとなります。今回の場合はHumanです。
push_backで最後尾に追加。
people[i]でi番目のHumanを取得。
こんな感じの処理です。
詳しくは下のページでもみてください。
http://www.wakhok.ac.jp/~sumi/stl/
fooさん詳しい解説とホームページありがとうございました。
今後の参考にしてみます^−^
ツイート | ![]() |