关于C++创建类时出现的错误
- C/C++ code
#include<iostream>#include<string>using namespace std;class people{public: people() { /* string n,s; int age; cout<<"请分别输入姓名,年龄,性别"<<endl; cin>>n>>a>>s; name=n; age=a; sex=s;*/ } void input() { string n,s; int a; cout<<"请分别输入姓名,年龄,性别"<<endl; cin>>n>>a>>s; name=n; age=a; sex=s; }void show () { cout<<"name:"<<name<<"tage:"<<age<<"tsex"<<sex<<endl; }private: string name; int age; string sex;};int main(){ int num=1; cout<<"多少人?"<<endl; cin>>num; people *student; student=new people[num]; for(int a=num;a>=0;a--) { student[num].input(); } for(int b=1;b<=num;b++) { student[b].show(); } delete[]student; return 0; }编译无错, 运行出错, 希望大家给个意见。还有,假如不用这种方式创建对象,还有什么方式达到我的目的(安用户的需求创建对象)吗? 或者不适合用类去解决? 本人很菜, 希望得到详细的解答,谢谢。
[解决办法]
是你一开始的string对象的内存容量不够,导致后来输入后,拷贝对象处错了
[解决办法]
数组从0开始 接受到的num 最后一个为num-1
for (int i = 0;i < num;i++)
{
student[i].input();
}
[解决办法]
people *student[100];
for(int i=0;i<100;i++)
{
student[i]=new people()
}