/* 输出分离与输出抽象 */
#include <cstring>
#include <cstdio>
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 //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 )
{//Writer的send函数char类型参数与MyString提取字符函数的耦合
char c = s[i];
w.send( &c, 1 ); //Writer与MyString的耦合
}
}
int main()
{
FileWriter fw1( stdout );
MyString s = "Hello";
fw1 << s;
FILE* f = fopen( "d:\\1.txt","w" );
FileWriter fw2(f);
fw2 << s;
fclose(f);
return 0;
}
输出分离与输出抽象
于 2023-11-22 13:48:23 首次发布
本文介绍了一个C++程序,涉及类`Writer`和其子类`FileWriter`,以及`MyString`类。重点展示了如何通过`send`方法实现输出抽象,并在`main`中演示了`MyString`与`FileWriter`的耦合使用,以及文件I/O操作。
9万+

被折叠的 条评论
为什么被折叠?



