【C++OJ拷贝构造】电话号码升位(拷贝构造函数)
题目描述
输入
输出
输入样例
输出样例
参考代码
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class CTelNumber
{
private:
char *s; //包含1个字符指针数据成员,用于动态创建一个字符数组,然后保存外来输入的电话号码
public:
CTelNumber() {} //无参构造函数
CTelNumber(char *p) //构造函数
{
s = new char[8]; // new空间,长度是7+1
strcpy(s, p);
}
CTelNumber(CTelNumber &p) //拷贝构造函数,用原来7位号码的对象升位为8位号码对象
{
s = new char[9];
if (p.s[0] == '2' || p.s[0] == '3' || p.s[0] == '4') //原2、3、4开头的电话号码前面加8
{
s[0] = '8';
}
else if (p.s[0] == '5' || p.s[0] == '6' || p.s[0] == '7' || p.s[0] == '8') //原5、6、7、8开头的前面加2
s[0] = '2';
for (int i = 0; i < 7; i++)
{
s[i + 1] = p.s[i]; //赋值后面7位数
}
}
void print() //打印函数
{
for (int i = 0; i < 8; i++)
cout << s[i];
cout << endl;
}
~CTelNumber() //析构函数
{
delete[] s;
}
};
bool isLegal(char *p)
{
int i;
if (p[0] <= '1' || p[0] >= '9')
return false;
for (i = 0; i < 8 && p[i] != '\0' && p[i] >= '0' && p[i] <= '9'; i++)
;
return i >= 7;
}
int main()
{
int t;
cin >> t;
char *p;
while (t--)
{
p = new char[8];
cin >> p;
if (isLegal(p))
{
CTelNumber c1(p);
CTelNumber c2(c1);
c2.print();
}
else
cout << "Illegal phone number" << endl;
}
}