发布网友 发布时间:2022-04-23 02:25
共3个回答
热心网友 时间:2023-08-24 10:37
#include<iostream>
#include<string>
using namespace std;
class Student
{
string sid;
string sname;
static int n;
public:
Student(); //无参构造函数
Student(string id,string name);//有参构造函数
Student(Student &stu);//复制构造函数
void output();//输出学号和姓名
static void showStuNum();//输出静态变量n
};
Student::Student()
{
sid="";
sname="";
n++;
}
Student::Student(string id,string name)
{
sid=id;
sname=name;
n++;
}
Student::Student(Student &stu)
{
sid=stu.sid;
sname=stu.sname;
n++;
}
void Student::output()
{
cout<<"编号:"<<sid<<endl;
cout<<"姓名:"<<sname<<endl;
}
void Student::showStuNum()
{
cout<<"已创建学生个数:"<<n<<endl;
}
int Student::n=0;
void main()
{
Student stud1;
Student stud2("200832570056","王明");
Student stud3(stud2);
stud1.output();
stud2.output();
stud3.output();
Student::showStuNum();
}
热心网友 时间:2023-08-24 10:37
代码如下:开发环境:VS2005+XP:
#include <iostream>
using namespace std;
class student
{
public:
student()
{
sid = 0;
sname = new char [1];
sname[0]='\0';
++ n;
};
student( int id, char * name )
{
sid = id;
int iLen = strlen( name );
sname = new char [iLen+1];
memset( sname, 0, iLen+1 );
strcpy( sname, name );
++ n;
}
student( student & std )
{
this->sid = std.sid;
int iLen = strlen( std.sname );
sname = new char [iLen+1];
memset( sname, 0, iLen+1 );
strcpy( sname, std.sname );
++ n;
}
~student()
{
if ( sname != 0 )
{
delete [] sname;
}
}
int GetID( void )
{
return sid;
}
char *GetName( void )
{
return sname;
}
static int GetStdNum( )
{
return n;
}
private:
int sid;
char * sname;
static int n;
};
// 使用上述代码
int student::n = 0;
int main()
{
student std1;
student std2( 1, "li gang");
student std3(std2);
printf( "std1.id = %d, std1.sname = %s\n", std1.GetID( ), std1.GetName( ));
printf( "std2.id = %d, std2.sname = %s\n", std2.GetID( ), std2.GetName( ));
printf( "std3.id = %d, std3.sname = %s\n", std3.GetID( ), std3.GetName( ));
printf( "there are %d students\n", student::GetStdNum( ));
}
有不清楚的地方可以再联系我
热心网友 时间:2023-08-24 10:38
#include <iostream.h>
#include <string.h>
class Student
{
private:
char sid[10];
char sname[20];
static int n;
public:
Student();
Student(char *id,char *name);
Student(const Student &stu);
void DispID();
void DispName();
static void DispCount();
};
Student::Student()
{
strcpy(sid,"999");
strcpy(sname,"无名");
n++;
}
Student::Student(char *id,char *name)
{
strcpy(sid,id);
strcpy(sname,name);
n++;
}
Student::Student(const Student &stu)
{
strcpy(sid,stu.sid);
strcpy(sname,stu.sname);
n++;
}
void Student::DispCount()
{ cout<<" 共 "<<n<<" 名学生";
}
void Student::DispID()
{ cout<<"学号:"<<sid;
}
void Student::DispName()
{ cout<<" 姓名:"<<sname;
}
int Student::n=0;
void main()
{
Student s1;
s1.DispID();s1.DispName();Student::DispCount();cout<<endl;
Student s2("1001","李大鹏");
s2.DispID();s2.DispName();Student::DispCount();cout<<endl;
Student s3=s2;
s3.DispID();s3.DispName();Student::DispCount();cout<<endl;
}