C++的类

主要讲述类的对象的构造过程,析构过程.

1.data.h主要进行简单的声明

#include "stdio.h"
#include "iostream.h"
#include <string>
#if !defined(AFX_123)

class CStudent
{
private:
char* age;
char* name;

public:
char* GetName() const;
void SetName(char*);
void display(void);

CStudent(int,char*); CStudent(const CStudent&); ~CStudent(); }; #define AFX_123 #endif

2. 在cpp实现上述处理

#include "data.h"

char* CStudent::GetName() const
{
return name;
}void CStudent::SetName(char* name)
{
this->name=name;
}
void CStudent::display(void)
{
cout<<"成员函数输出成员数据"<<name<<endl;
}

void CStudent::CStudent(int age,char* strName) //浅拷贝构造函数
{
this->age=age;
name=new char[strlen(strName)+1];
if(name!=NULL)
strcpy(this->name,strName);
}
CStudent::CStudent(const CStudent& steStu) //深拷贝构造函数
{
this->age=theStu.age;
this->name=new char[strlen(theStu.name)+1];
if(this->name!=NULL)
strcpy(this->name, theStu.name)
}

CStudent::~CStudent() {
if(name!=NULL)
delete name; }
void main()
{
CStudent stu(10,"小上海");
cout<<"display info:"<<stu.age<<endl;
cout<<"display info:"<<stu.name<<endl;

CStudent newStudent( stu );//调用深拷贝构造函数 :值传递(参数,返回值,赋值运算)
cout<<"display info:"<<stu.age<<endl;
cout<<"display info:"<<stu.name<<endl;

stu.display(); //1
newStudent.display(); //2
} //如果没有深度拷贝函数的话,执行完上述的1. 2.之后,将会出项错误.

 

posted @ 2013-01-03 11:53  血洗女生宿舍  阅读(188)  评论(0编辑  收藏  举报