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

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


相关文章:

  • 2022-12-23
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-15
  • 2021-07-21
  • 2021-04-16
猜你喜欢
  • 2022-12-23
  • 2021-11-17
  • 2021-10-31
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-16
相关资源
相似解决方案