#include
#include
class Writer{
public:
virtual ~Writer() { };
virtual void send(const char*, int ) = 0;
};
class FileWriter:public Writer{
public:
FileWriter( FILE*f );
void send(const char*p, int n );
private:
FILE*fp;
};
class MyString
{
char *p;
public:
MyString();
MyString(const char *s);
MyString(const MyString & x);
MyString & operator=(const MyString & x);
~MyString();
char & operator[](int x)const;
int size()const;
};
FileWriter::FileWriter( FILE*f ):fp(f) { }
void FileWriter::send(const char* p, int n ){
for(int i=0; i<n; ++i)
putc(*p++, fp );
}
MyString::MyString(){ p = NULL; }
MyString::MyString(const char *s){
p = new char[strlen(s)+ 1];
strcpy(p,s);
}
MyString::MyString(const MyString & x)
{
if(x.p){
p = new char[strlen(x.p)+1];
strcpy(p,x.p);
}
else
p = NULL;
}
MyString& MyString::operator=(const MyString & x)
{
if(p == x.p)
return *this;
if(p)
delete[] p;
if(x.p)
{
p = new char[strlen(x.p)+1];
strcpy(p,x.p);
}
else
p = NULL;
return *this;
}
MyString::~MyString(){ if(p)delete []p; }
char& MyString::operator[](int x)const{ return p[x]; }
int MyString::size()const { if(p) return strlen(p) ; return 0; }
Writer& operator << ( Writer& w, const MyString& s ){
for( int i=0; i < s.size(); ++i )
{
char c = s[i];
w.send( &c, 1 );
}
}
int main()
{
FileWriter fw1( stdout );
MyString s = "Hello";
fw1 << s;
FILE* f = fopen( "d:\\1.txt","w" );
FileWriter fw2(f);
fw2 << s;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91