北大程序設計與算法(三)測驗題彙總(2020春季)
描述
補足MyString類,使程序輸出指定結果
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString {
char * p;
public:
MyString(const char * s) {
if( s) {
p = new char[strlen(s) + 1];
strcpy(p,s);
}
else
p = NULL;
}
~MyString() { if(p) delete [] p; }
// 在此處補充你的代碼
};
int main()
{
char w1[200],w2[100];
while( cin >> w1 >> w2) {
MyString s1(w1),s2 = s1;
MyString s3(NULL);
s3.Copy(w1);
cout << s1 << "," << s2 << "," << s3 << endl;
s2 = w2;
s3 = s2;
s1 = s3;
cout << s1 << "," << s2 << "," << s3 << endl;
}
}
輸入
多組數據,每組一行,是兩個不帶空格的字符串
輸出
對每組數據,先輸出一行,打印輸入中的第一個字符串三次,然後再輸出一行,打印輸入中的第二個字符串三次
樣例輸入
abc def
123 456
樣例輸出
abc,abc,abc
def,def,def
123,123,123
456,456,456
來源
Guo Wei
分析
MyString s1(w1)
需要構造函數,題目已經給出;
MyString s2 = s1
需要複製構造函數;
s2 = w2;
需要臨時構造函數;
s3 = s2;s1 = s3;
需要等號運算符的重載;
解答
void Copy(const char * s){
if(p)
delete []p;
if(s){
p = new char[strlen(s) + 1];
strcpy(p,s);
}
else
p = NULL;
}
friend ostream &operator<<(ostream &o,const MyString & s){
o << s.p;
return o;
}
MyString (const MyString & s) {
if( s.p ) {
p = new char[strlen(s.p)+1];
strcpy(p,s.p);
}
else {
p = NULL;
}
}
MyString &operator = (const MyString & s){
if(this == &s)
return *this;
if(s.p)
{
if(p)
delete []p;
p = new char[strlen(s.p) + 1];
strcpy(p,s.p);
}
else
p = NULL;
return *this;
}
執行效果