发表文章

[最新] 类成员初始化举例

micro9981 2011-8-30 65

代码:

#include <iostream>   
#include <cstring>   
using namespace std;     

class StudentID
{
 public:
 StudentID(int id=1)
 {
  value=id;
  cout <<"Assigning student id " <<value <<endl;
 }
 ~StudentID()
 {
  cout <<"Destructing id " <<value <<endl;
 }
 protected:
  int value;
};

class Student{
 public:
 Student(char* pName="noName",int ssID=0)
 {
  cout <<"Constructing student " <<pName <<endl;
  strncpy(name,pName,sizeof(name));
  name[sizeof(name)-1]='\0';
  StudentID id(ssID);
 }
 protected:
  char name[20];
       StudentID id;
};

int main()
{
 Student s("Randy",9818);
}


 编译运行结果:
Assigning student id 1
Constructing student Randy
Assigning student id 9818
Destructing id 9818
Destructing id 1


 

 

相关推荐
最新评论 (0)
返回
发表文章
micro9981
文章数
605
评论数
0
注册排名
919760