1. 程式人生 > >C++中類的資料成員是字串

C++中類的資料成員是字串

可以用分別使用:字元陣列,string類的物件,字元指標表示字串。實現方法略有不同。

#include <iostream>

#include <string>

using namespace std;

class CStudent

{

private:

       int number;

       char name[20];

       string addr;

       char *email;

       int age;

public:

       CStudent(int xh=0, char *xm="Noname", string ad="Noad",char *em="Noemail",int a=18);

       CStudent(CStudent & s);

       ~CStudent( );

       void setStudent(int xh=0, char *xm="Noname", string ad="Noad",char *em="Noemail",int a=18);

       void printStudent( );

       int GetAge( );

};

CStudent::CStudent(int xh, char *xm, string ad,char *em,int a)

{     number = xh;

       strcpy(name, xm);

       addr=ad;

       email=new char[strlen(em)+1];strcpy(email, em);

       age = a;    }

CStudent::    CStudent(CStudent & s){

              if(this!=&s){

                     number = s.number;

                     strcpy(name, s.name);

                     addr=s.addr;

                     email=new char[strlen(s.email)+1];strcpy(email, s.email);

                     age = s.age;   

              }

       }

void CStudent::setStudent(int xh, char *xm, string ad,char *em, int a)

{     number = xh;

       strcpy(name, xm);

       addr=ad;

       delete []email;

       email=new char[strlen(em)+1];strcpy(email, em);

       age = a;    }

CStudent::~CStudent( ){

              delete [ ]email;

              //cout<<number<<endl;

       }

void CStudent::printStudent(){

    cout<<number<<" "<<name<<" "<<addr<<" "<<email<<" "<<age<<endl;}

int CStudent::GetAge()

{     return age;}

int main()

{

       int sum=0;

       CStudent s[8] = { CStudent(10000, "AAAAAA", "shanghai", "[email protected]", 20),

                             CStudent(10001, "BBBBBB", "qinghai", "[email protected]",22 ),

                             CStudent( ),CStudent( ),

                             CStudent(10004, "EEEEEE", "shangdang", "[email protected]",18 )

                             };

    s[2].setStudent(10002, "CCCCCC", "weihai", "[email protected]",24 );

    s[3].setStudent(10003, "DDDDDD", "shandong", "[email protected]",21 );

    s[5].setStudent(10005, "FFFFFFF", "heihai", "[email protected]",23 );

    s[6].setStudent(10006, "GGGGG", "shanxi", "[email protected]",20 );

    s[7].setStudent(10007, "HHHHH", "jiangsu", "[email protected]",20 );

       for(int i=0; i<8; i++)

       {   sum += s[i].GetAge();

        s[i].printStudent();}

       cout << sum/8 << endl;

       return 0;

}