构造函数和类型转换,在构造函数中强制转换,

当构造函数只有一个参数(或者有多个参数,但是其他参数都带有默认值,(有默认值的参数靠右排放),这样就可以在调用的时候只传一个参数,)就可以被用来做类型转换,

#include<iostream>
#include<string.h>
using namespace std;
class String
{
	int  len ;
	char * rep;
public:
	String():len(0)
	{
		rep=new char[1];
		strcpy(rep,"");
	}
	String(char* s)
	{
		if(!s)
		{
			len=0;
			rep=new char[1];
			strcpy(rep,"");
		}
		else
		{
			len=strlen(s);
			rep=new char[len+1];
			strcpy(rep,s);
		}
		
	}
	String(const String &str):len(str.len),rep(new char[len+1])
	{
		strcpy(rep,str.rep);
	}
	~String()
	{
		delete[] rep;
	}
	friend void print(const String& s);

};
void print(const String& s )
{
	cout<<s.rep<<endl;
	return;
}



int main()
{
	char* a="hello kity";
	print(a);
	String b="bad ";
	print(b);
	return 0;
}


posted @ 2013-08-01 18:57  shouqiang Wei  阅读(340)  评论(0编辑  收藏  举报