注册 登录
编程论坛 C++教室

这个程序应该如何改?

louchenggang 发布于 2017-10-04 14:33, 1517 次点击
#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; }
   
    /* MyString & operator = (const char *w)
     {
          delete [] p;
          p=new char[strlen(w)+1];
          strcpy(p,w);
          return *this;
     }
     
     void Copy(char *s)
     {
         delete [] p;
         p=new char[strlen(s)+1];
         strcpy(p,s);
     }
     friend ostream & operator << (ostream & o,const MyString & s);
     ostream & operator << (ostream & o,const MyString & s)
     {
         o<<s.p;
        return o;
     }
     注释部分,是我修改部分,编译时候出现错误,应该如何修改呢?
     ostream & operator << (ostream & o,const MyString & s) 报错
     [Error] 'std::ostream& MyString::operator<<(std::ostream&, const MyString&)' must take exactly one argument
     */
};
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

[此贴子已经被作者于2017-10-4 14:40编辑过]

1 回复
#2
rjsp2017-10-09 08:32
你题目说清了吗?
如果是,为什么不用 std::string?
char w1[200],w2[100] --- 题目中有说第一个字符串不超过199字符,第二个字符不超过99字符吗?
1