实验目的:
1. 掌握动态分配对象的方法
2. 掌握动态分配对象数组的方法- #include <iostream>
-
#include <cstring> //在 vc6.0 下 使用#include<string.h>
-
//在 g++ 环境 为 cstring
-
-
using namespace std;
-
class CStudent
-
{
-
public:
-
CStudent();//构造函数 没有返回值
-
CStudent(char *name,int age); //定义一个带参 构造函数
-
~CStudent(); //析构函数,唯一,不能重载
-
-
CStudent &init(char *name,int age); //赋值功能
-
void output(); //输出类对象的两个数据成员
-
private:
-
char name[20];
-
int age;
-
};
-
-
CStudent::CStudent() //无参构造函数
-
{
-
strcpy(this->name," ");
-
this->age=0;
-
}
-
-
CStudent::CStudent(char *name,int age) //带参 构造函数实现
-
{
-
strcpy(this->name,name);
-
this->age=age;
-
}
-
-
CStudent::~CStudent()
-
{
-
cout<<"the object is deconstructing..."<<endl;
-
}
-
-
CStudent &CStudent::init(char *name,int age)
-
{
-
strcpy(this->name,name);
-
this->age=age;
-
return (*this);
-
}
-
-
void CStudent::output()
-
{
-
cout<<this->name<<" "<<this->age<<endl;
-
}
-
下面的程序 不会进行析构,
- int main()
-
{
-
CStudent *p= new CStudent; //自动无参构造函数 初始化
-
p->output();
-
return 0;
-
}
- ywx@yuweixian:~/yu/c++/shiyan1$ ./student1
-
0
-
ywx@yuweixian:~/yu/c++/shiyan1$
我们需要自己 手动 删除- int main()
-
{
-
CStudent *p= new CStudent; //自动无参构造函数 初始化
-
p->output();
-
delete p;
-
return 0;
-
}
- ywx@yuweixian:~/yu/c++/shiyan1$ ./student1
-
0
-
the object is deconstructing...
-
ywx@yuweixian:~/yu/c++/shiyan1$
动态数组- int main()
-
{
-
CStudent *p= new CStudent; //自动无参构造函数 初始化
-
p->output();
-
delete p;
-
-
CStudent *q = new CStudent[2];
-
q[0].init("alice",22);
-
q[1].init("marry",23);
-
q[0].output();
-
q[1].output();
-
-
delete []q;
-
-
return 0;
-
}
- ywx@yuweixian:~/yu/c++/shiyan1$ ./student1
-
0
-
the object is deconstructing...
-
alice 22
-
marry 23
-
the object is deconstructing...
-
the object is deconstructing...
-
ywx@yuweixian:~/yu/c++/shiyan1$
阅读(547) | 评论(0) | 转发(0) |