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
  1. 在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();         //1newStudent.display();  //2}                      //如果没有深度拷贝函数的话,执行完上述的1.  2.之后,将会出项错误.

原文链接: https://www.cnblogs.com/girlblooding/archive/2013/01/03/2842799.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74375

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午4:22
下一篇 2023年2月9日 下午4:22

相关推荐