问题描述 :
实验目的:静态成员、构造函数、析构函数、等于号的使用。
实验内容:
实现一个自己的字符串类MyString,要求包含以下函数:
构造函数:
MyString(unsigned n,char c):将字符c重复n次得到字符串
MyString(char *p):根据传入的字符数组得到字符串
根据需要,还需要设计默认构造函数、拷贝构造函数等其它函数。
其中,MyString类需要提供一个静态方法GetCount,功能为获取到本程序在运行的过程中某时刻有多少个MyString的对象。
本次实验提供了部分代码,请使用以下代码调用MyString类的功能完成输入、处理、输出操作:
void fun1(int n)
{
MyString strArr[n];
MyString *pStr;
cout<<strArr[0].GetCount()<<endl;
}
void fun2(int n)
{
MyString *pStr=new MyString[n];
cout<<MyString::GetCount()<<endl;
}
void fun3(MyString &s1, MyString s2)
{
MyString s3;
s3=s1=s2;
cout<<MyString::GetCount()<<endl;
s3.ShowStr();
cout<<endl;
}
int main( )
{
MyString s1;
MyString s2;
int n;
char charArr[20];
int op;
while (cin >> op)
{
switch (op)
{
case 1:
{
cin>>n;
fun1(n);
break;
}
case 2:
{
cin>>n;
fun2(n);
break;
}
case 3:
{
int m;
char ch;
cin>>m>>ch;
s2=MyString(m,ch);
fun3(s1,s2);
s1.ShowStr();
cout<<endl;
break;
}
case 4:
{
cin >> charArr;
s1=MyString(charArr);
cout<<MyString::GetCount()<<endl;
s1.ShowStr();
cout<<endl;
break;
}
}
}
return 0;
}
输入说明 :
可输入多组测试数据,每组测试数据包含两行:
第一行输入一个操作的种类,
第二行输入所需要的参数:
对于第1个操作和第2个操作,第二行输入一个整数。
对于第3个操作,第二行输入一个整数及一个字符。
对于第4个操作,第二行输入一个字符串。
输出说明 :
具体输出见函数中的输出语句及输出范例。
输入范例 :
1
3
2
3
1
3
3
10 *
4
abcd
输出范例 :
5
5
8
7
**********
**********
5
abcd
解题代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
#include<set>
#include<vector>
#include<queue>
using namespace std;
class MyString {
public:
MyString(unsigned n, char c); //将字符c重复n次得到字符串
MyString(char* p); //根据传入的字符数组得到字符串
MyString();
~MyString();
void ShowStr();
static int count;
static int GetCount();
private:
string s;
};
int MyString::count = 0;
void MyString::ShowStr()
{
cout << s;
return;
}
MyString::MyString()
{
count++;
}
MyString::~MyString()
{
count--;
}
MyString::MyString(unsigned n, char c) //将字符c重复n次得到字符串
{
s = "";
while (n--)
s += c;
count++;
count++;
}
MyString::MyString(char* p) //根据传入的字符数组得到字符串
{
while (*p != '\0')
s += *p, p++;
count++;
}
int MyString::GetCount()
{
return MyString::count;
}
void fun1(int n)
{
MyString strArr[n];
MyString* pStr;
cout << strArr[0].GetCount() << endl;
}
void fun2(int n)
{
MyString* pStr = new MyString[n];
cout << MyString::GetCount() << endl;
}
void fun3(MyString& s1, MyString s2)
{
MyString s3;
s3 = s1 = s2;
cout << MyString::GetCount() << endl;
s3.ShowStr();
cout << endl;
}
int main()
{
MyString s1;
MyString s2;
int n;
char charArr[20];
int op;
while (cin >> op)
{
switch (op)
{
case 1:
{
cin >> n;
fun1(n);
break;
}
case 2:
{
cin >> n;
fun2(n);
break;
}
case 3:
{
int m;
char ch;
cin >> m >> ch;
s2 = MyString(m, ch);
fun3(s1, s2);
s1.ShowStr();
cout << endl;
break;
}
case 4:
{
cin >> charArr;
s1 = MyString(charArr);
cout << MyString::GetCount() << endl;
s1.ShowStr();
cout << endl;
break;
}
}
}
return 0;
}