输出分离与输出抽象

/* 输出分离与输出抽象 */

#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 //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;
}

你可能感兴趣的:(C++,c++)