#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";
}
}