(自用)手机服务(构造+拷贝构造+堆)中关于停机日期指针创建为动态对象,并根据参数来设置停机日期以及如何复制停机日期

#include <iostream>
#include <cstring>
using namespace std;
class Date {
private:
	int year, month, day;
public:
	Date(int y, int m, int d) {
		year = y;
		month = m;
		day = d;
	}
	int getYear() {
		return year;
	}
	int getMonth() {
		return month;
	}
	int getDay() {
		return day;
	}
};
class Phone {
private:
	char type;
	string num;
	int state;
	Date* stopdate;
public:
	Phone(char t1, string n1, int s1) {
		type = t1;
		num = n1;
		state = s1;
		stopdate = NULL;
		cout << "Construct a new phone " << num << endl;
	}
	Phone(const Phone& c) {
		num = c.num;
		cout << "Construct a copy of phone " << num << endl;
		num = c.num+'X';
		type = 'D';
		state = c.state;
		stopdate = NULL;
		if (c.stopdate != NULL) {
			stopdate = new Date(*c.stopdate);
		}
	}
	string getType() {
		switch (type) {
		case 'B':return"企业";
		case 'A':return"机构";
		case 'C':return"个人";
		case 'D':return"备份";
		}
	}
	string getState() {
		switch (state) {
		case 1:return"在用";
		case 2:return"未用";
		case 3:return"停用";
		}
	}
	void stop(Date& d) {
		state = 3;
		stopdate = new Date(d.getYear(), d.getMonth(), d.getDay());
		cout << "Stop the phone " << num << endl;
	}
	void print() {
		cout << "类型=" << getType() << "||号码=" << num << "||State=" << getState();
		if (state == 3) {
			cout << " ||停机日期=" << stopdate->getYear()<<'.'<<(*stopdate).getMonth()<<'.'<<stopdate->getDay() << endl;
		}
		else {
			cout << "\n";
		}
	}
	~Phone() {
		if (stopdate != NULL) {
			delete stopdate;
		}
	}
	
};
int main() {
	int t,s1,y1,m1,d1;
	char t1;
	string n1;
	cin >> t;
	while (t--) {
		cin >> t1 >> n1 >> s1 >> y1 >> m1 >> d1;
		Date c(y1, m1, d1);
		Phone a(t1, n1, s1);
		a.print();
		Phone b(a);
		b.print();
		a.stop(c);
		a.print();
		cout << "----" << endl;
	}
}

如果需要在一个类中调用另一个类中的内容,可以

private:
	Date* stopdate;

将停机日期指针创建为动态对象,并根据参数来设置停机日期

我认为可以理解成使stopdate指针与c.stopdate指针所指内容一致。。。所以要变成new Date(*c.stopdate)

if (c.stopdate != NULL) {
			stopdate = new Date(*c.stopdate);
		}//如果已有对象(被拷贝的)的停机日期不为空,则拷贝构造中要复制已有对象的停机日期↑

细品

void stop(Date& d) {
		state = 3;
		stopdate = new Date(d.getYear(), d.getMonth(), d.getDay());
		cout << "Stop the phone " << num << endl;
	}
	void print() {
		cout << "类型=" << getType() << "||号码=" << num << "||State=" << getState();
		if (state == 3) {
			cout << " ||停机日期=" << stopdate->getYear()<<'.'<<(*stopdate).getMonth()<<'.'<<stopdate->getDay() << endl;
		}
		else {
			cout << "\n";
		}
	}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值