这个程序怎么输出的数字很乱啊,貌似输入有问题,求指教#includeiostreamusing namespace stdclass stude
这个程序怎么输出的数字很乱啊,貌似输入有问题,求指教
#include<iostream>
using namespace std;
class student
{
private:
char name[20];
int ID;
int age;
public:
student(char name[20],int ID,int age);
void display(){cout << "here is the student's information"<<endl
<< "name:" << name[20]<<endl
<< "ID:" << ID<<endl
<< "age" << age <<endl;}
};
student::student(char name[],int ID,int age){
cin >> *name >>ID >> age;
}
int main()
{
char name[20];
int ID = 0;
int age = 0;
memset(name,0,sizeof(name));
cout <<"Input student's information:" << endl;
student stu(name,ID,age);
stu.display();
return 0;
}
[解决办法]
<< name[20]
改成 << name
cin >> *name >>ID >> age;
改成 >> name
memset(name,0,sizeof(name));
没事不要用,尽量用constructor初始化class的资料
这东西只对POD管用
[解决办法]
说明见注释。
- C/C++ code
#include<iostream>using namespace std;class student{ private: char name[20]; int ID; int age;public: student(); void display(){ cout << "here is the student's information"<<endl << "name:" << name<<endl //直接指针来输出字符串 << "ID:" << ID<<endl << "age:" << age <<endl;}};//student::student(char name[],int ID,int age){// cin >> *name >>ID >> age; //形式化参数会覆盖类的成员变量,是类的成员变量得不到赋值//}student::student(){ //既然是从标准输入中获得对象的初始化数据,那么就需要从外部输入 cin >> name >>ID >> age; //直接指针来接受字符串}int main(){ //char name[20]; //int ID = 0; //int age = 0; //memset(name,0,sizeof(name)); cout <<"Input student's information:" << endl; student stu; stu.display(); return 0;} 