用字符串string类来接收和显示字符串,可直接赋值字符串,不再需要strcpy函数,基本用法如下:
string str="Thank you";
str+=" very much!";
cout<<str<<endl;
str="I Love C++!";
cout<<str<<endl;
声明一个Person类,private成员4个:身份证号(ID,用string类型),姓名(string类型),性别(string类型),出生年月日(string类型,比如"2003-10-01")。构造函数有4个形式参数,分别赋值给4个私有成员。public成员四个:getID, getName,getSex,getBirthday,分别输出以上四个私有成员的值。
再编写一个Student类,public继承Person类,新增private数据成员是班级(可用string类型,比如"电科班","光信班")和专业成绩(float类型,0-100分),Student类构造函数需要显示调用Person类构造函数,形式参数分别是Person所需四个参数以及新增两个参数,在函数体内将新增两个参数赋值给两个新增private成员。public成员两个:getClass,getScore,分别输出两个新增private成员的值。
main函数中定义一个Student类对象,
Student *stu=new Student(形式参数表列);
用public函数输出各个private成员的值(共6个)。
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
class Person
{
public:
Person(string newID,string newname,string newsex,string newbirthday)
{
ID=newID;
name=newname;
sex=newsex;
birthday=newbirthday;
}
void getID()
{
cout<<ID<<endl;
}
void getName()
{
cout<<name<<endl;
}
void getSex()
{
cout<<sex<<endl;
}
void getBirthday()
{
cout<<birthday<<endl;
}
private:
string ID;
string name;
string sex;
string birthday;
};
class Student:public Person
{
public:
Student(string newID,string newname,string newsex,string newbirthday,string newclass,float newscore):Person(newID,newname,newsex,newbirthday)
{
Class=newclass;
score=newscore;
}
void getClass()
{
cout<<Class<<endl;
}
void getScore()
{
cout<<score<<endl;
}
private:
string Class;
float score;
};
int main()
{
Student *stu=new Student("5226","李虎","Man","2005-12-25","a班",96.63);
stu->getID();
stu->getName();
stu->getSex();
stu->getBirthday();
stu->getClass();
stu->getScore();
delete stu;
return 0;
}