64,690
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int n,string nam,char s) //定义构造函数
{
num = n;
name = nam;
sex = s;
cout << "Constructor called." << endl;
}
~Student() //定义析构函数
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
char name[10];
char sex;
};
int main()
{
Student stud1(10010,"Wang_li",'f'); //建立对象stud1
stud1.display(); //输出stud1的数据
Student stud2(10011,"Zhang_fun",'m');
stud2.display();
return 0;
}
class Student
{
public:
Student(int n,string nam,char s) //定义构造函数
{
const char *na;
num = n;
na = nam.c_str(); //用c_str操作
memcpy(name,na,strlen(na) );
sex = s;
cout << "Constructor called." << endl;
}
~Student() //定义析构函数
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
char name[10];
char sex;
};
int main()
{
Student stud1(10010,"Wang_li",'f'); //建立对象stud1
stud1.display(); //输出stud1的数据
Student stud2(10011,"Zhang_fun",'m');
stud2.display();
return 0;
}
name = nam;
改为
strcpy(name,nam.c_str());
#include<iostream>
#include<string>
#include <stdio.h>
using namespace std;
class Student
{
public:
Student(int n,string nam,char s) //定义构造函数
{
num = n;
//name = nam;
strcpy(name, nam.c_str());
sex = s;
cout << "Constructor called." << endl;
}
~Student() //定义析构函数
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
char name[10];
char sex;
};
int main()
{
Student stud1(10010,"Wang_li",'f'); //建立对象stud1
stud1.display(); //输出stud1的数据
Student stud2(10011,"Zhang_fun",'m');
stud2.display();
return 0;
}