このプログラムをコンパイルして名前を入力すると、実行エラーがでます。
なぜでしょうか?
コンパイラー Visual C++
後実行させたい事は、生徒の名前と年を入力させて、表示させたいんです。
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
//Demographic class
class Demographic{
int age;
char *name;
public:
Demographic( char *s, int a ){strcpy(name,s); age = a;}
void call(){cout << "\t Student Name is " << name << endl; cout << "\t Student Age is " << age << endl;}
};
//Generation Class
class Generation{
public:
Generation(){};
void Make();
};
void Generation::Make(){
char *StName = "0";
int StAge;
cout << "\t Please enter your students' name and age." << endl;
cout << "\t Student Name :: ";
cin >> StName;
cout << "\n\t Student Age ::";
cin >> StAge;
Demographic St( StName,StAge );
system("cls");
St.call();
}
int main(){
Generation A;
A.Make();
return 0;
}
実行時エラーの起こる場所と,エラーメッセージを記述するようにしてください。
> Demographic( char *s, int a ){strcpy(name,s); age = a;}
nameが指す記憶域は,どこで確保したのですか?
> cin >> StName;
文字列リテラル領域を書き換えることは未定義動作です。
行ってはいけません。
簡単にしか見ていませんが,こんなところでしょうか。
それから,<iostream.h>は古いヘッダファイルです。
#例えば,VC++.NET 2003ではサポートされない。
<iostream>のような,新しいヘッダファイルを利用しましょう。
Demographicクラスのメンバ変数 name にはメモリが割り当てられていません。
コンストラクタで strcpy する前にnewやらmallocでメモリを確保する必要があります。(また、デストラクタなどでdeleteまたはfreeしなければなりません。)
返事ありがとうございます。
えーと、私は最近プログラムを始めたばかりで、
多々分からない事があります。
できたら、どうやってやればいいか教えていただけますか?
一応今malloc関数を使用して初期化しました。
ですが今度はこんなエラーがでました。
no operator defined which takes a right-hand operand of type 'int *' (or there is no acceptable conversion)
一応必要な関数は全て定義してるはずなんですがなぜでしょうか?
もう一度ソースを載せますね^−^;
度々すいません。
#include <iostream.h>
#include <string>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
using namespace std;
//Demographic class
class Demographic{
int *age;
char *name;
public:
Demographic( char *s, int *a ){name = (char *)malloc(sizeof(char)*30); age = (int *)malloc(sizeof(int)*30);strcpy(name,s); age = a;}
void call(){cout << "\t Student Name is " << name << endl; cout << "\t Student Age is " << age << endl;}
};
//Generation Class
class Generation{
public:
Generation(){};
void Make();
};
void Generation::Make(){
char *StName;
int *StAge;
StName = (char *)malloc(sizeof(char)*30);
StAge = (int *)malloc(sizeof(int)*30);
cout << "\t Please enter your students' name and age." << endl;
cout << "\t Student Name :: ";
cin >> StName;
cout << "\n\t Student Age ::";
cin >> StAge;
Demographic St( StName,StAge );
system("cls");
St.call();
}
int main(){
Generation A;
A.Make();
return 0;
}
class Demographicのageと、Generation::Make()内のStAgeは
mallocの必要は無いと思いますが。
というかint*型にする必要すらないと…
あと、malloc()/calloc()で確保するならば、不要になった時にfree()すべきです。
プログラム終了時にOSが後始末してくれるでしょうが、ソレを期待したコードを書くべきではありません。
# ついでに…C++ならnewまたはnew[]/deleteまたはdelete[]にすべきかと。
そもそも,ポインタなんか使わなくてもよいはず……。
せっかくstring型なんてのがあるんだし……。
色々ありがとうございます^−^;
ちょっとまだ勉強不足何で.....
じゃとりあえずNEWとDELETEを使用したプログラムを作成してみます。
後このプログラムで、多数生徒の名前と年を入力できるようにする予定です。
ありがとうございました。
ツイート | ![]() |