关于C++创建类时出现的错误

haxer 2012-06-03 04:09:35
#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;


}

编译无错, 运行出错, 希望大家给个意见。还有,假如不用这种方式创建对象,还有什么方式达到我的目的(安用户的需求创建对象)吗? 或者不适合用类去解决? 本人很菜, 希望得到详细的解答,谢谢。
...全文
111 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
code_sheep 2012-06-04
  • 打赏
  • 举报
回复
people *student[100];
for(int i=0;i<100;i++)
{
student[i]=new people()
}
haxer 2012-06-03
  • 打赏
  • 举报
回复
我把main 函数改成这样还是不行:
int main()
{
int num=1;
cout<<"多少人?"<<endl;
cin>>num;
people *student;
student=new people[num];
for(int a=0;a<num;a++)
{
student[num].input();
}
for(int b=0;b<num;b++)
{
student[b].show();
}
delete[]student;
return 0;


}
艳琦罗生 2012-06-03
  • 打赏
  • 举报
回复
数组从0开始 接受到的num 最后一个为num-1
for (int i = 0;i < num;i++)
{
student[i].input();
}
W170532934 2012-06-03
  • 打赏
  • 举报
回复
是你一开始的string对象的内存容量不够,导致后来输入后,拷贝对象处错了

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧