題目
描述
補足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);}elsep = 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 (s){p = new char[strlen(s) + 1];strcpy(p, s);}else{p = NULL;}}MyString(const MyString& m){if (m.p){p = new char[strlen(m.p) + 1];strcpy(p, m.p);}else{p = NULL;}}friend ostream& operator<< (ostream& o, MyString& m){o << m.p;return o;}MyString& operator= (const MyString& m){if (m.p){p = new char[strlen(m.p) + 1];strcpy(p, m.p);}else{p = NULL;}return *this;}MyString(){}