实验六
实验六:类和对象(二)
实验目的: (1)掌握类的构造函数和析构函数的使用方法 (2)掌握对象数组和对象指针的使用方法
实验内容: 重新编写实验五中的时间类Time,增加3个构造函数:缺省 构造函数、带3个参数的构造函数以及拷贝构造函数。要求: (1)利用不同的构造函数创建新对象; (2)利用new和delete运算符创建和撤销对象; (3) 创建一个对象数组,分别利用数组下标和对象指针实现对 数组元素的遍历。
time.h
#ifndef TIME_H_INCLUDED #define TIME_H_INCLUDED using namespace std; class Time { public: Time(); Time(int ,int ,int );//构造函数 Time(const Time&); ~Time(); void Set(int h,int m,int s);//不加的话会出现 has no member named 报错 void Show(); private: int hour; int minute; int second; }; #endif // TIME_H_INCLUDED
time.cpp
#include "time.h" #include <iomanip> #include <iostream> using namespace std; Time::Time() { hour=0; minute=0; second=0; cout<<"Default Constructor"<<endl; } Time::Time(int h,int m,int s) { hour=h; minute=m; second=s; cout<<"3-Parameter Constructor"<<endl; } Time::~Time() { cout<<"("<<hour<<','<<minute<<','<<second<<")"<<' '<<"Delete finished"<<endl; } Time::Time(const Time& t) { hour=t.hour; minute=t.minute; second=t.second; cout<<"Copy Constructor"<<endl; } void Time::Set(int h,int m,int s) { hour=h,minute=m,second=s; } void Time::Show() { cout<<setw(2)<<setfill('0')<<hour<<":"<<setw(2)<<setfill('0')<<minute<<":"<<setw(2)<<setfill('0')<<second; if(hour<=12)cout<<" AM"<<endl; else cout<<" PM"<<endl; }
client.cpp
#include <iostream> #include "time.h" //#include "time.cpp" 如果没有链接文件的话不加的话会出现undefined reference to报错 但如果链接了就不能再加了 会出现分别编译头文件 using namespace std; int main() { Time time1(1,1,1);//带三个参数的构造函数 time1.Show(); cout<<"*********************************************************"<<endl; Time time2;//缺省构造函数 time2.Show(); cout<<"*********************************************************"<<endl; Time time3=time1;//拷贝构造函数 time3.Show(); cout<<"*********************************************************"<<endl; Time *time4=new Time(3,4,5); time4->Show(); delete time4;// cout<<"*********************************************************"<<endl; Time timeArray[3]={Time(1,15,37),Time(12,6,4),Time(7,22,53)}; cout<<"下标遍历"<<endl; for(int i=0;i<=2;i++) { timeArray[i].Show(); } cout<<"*********************************************************"<<endl; cout<<"指针遍历"<<endl; Time *pointer=timeArray; for(;pointer-timeArray<=2;pointer++) { pointer->Show(); } return 0; } //灰色无法编译:可能没保存/有打开的程序 //关于拷贝构造函数的const问题 如果不加const的话 类数组里用构造函数初始化会报错 //对象数组初始化的过程我觉得就是先生成一个实例 //然后编译器通过某种操作 //想要把这个const的实例引用通过拷贝函数传给对象数组 //但对象数组的拷贝函数是非const的 //参数不匹配就报错了 //一开始写成了delete(&time4) 应该是delete time4; time4本身就是指针 //缺省构造函数实例对象的话不能写成Time time() 要把括号去掉
//delete和new是互逆的,delete只能删除new出来的动态内存,用delete删除静态数组时不会报错但是最后会异常退出。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!