实现Stirng类:普通构造、复制构造、赋值函数、重载输出函数 <<(友元)

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std; class String
{
public:
String (const char *str=NULL); //普通构造函数
String (const String &other); //复制构造函数
~String (void); //析构函数
String &operator=(const String &other); //赋值函数
friend ostream &operator<<(ostream &output, const String &other); //输出函数
private:
char *data; //保存字符串
}; //普通构造函数
String::String(const char *str)
{
if (str == NULL)
{
data = new char[];
*data = '\0';
}
else
{
int len = strlen(str);
data = new char[len+];
strcpy(data, str);
}
} //复制构造函数
String::String(const String &other)
{
int len = strlen(other.data);
data = new char[len+];
strcpy(data, other.data);
} //析构函数
String::~String()
{
delete[] data;
} //赋值函数
String &String::operator=(const String &other)
{
if (this == &other)
{
return *this;
}
delete[] data; int len = strlen(other.data);
data = new char[len+];
strcpy(data, other.data); return *this;
} //输出函数
ostream &operator<<(ostream &output, const String &other)
{
output<<other.data;
return output;
} int main()
{
String s1("hello");
cout << s1 << endl;
String s2=s1;
cout << s2 << endl;
String s3;
s3=s1;
cout << s3 << endl;
}

最新文章

  1. linux基本命令
  2. PE启动菜单修改工具 MsgDiyer(GfxMenu Message制作工具) V2.0.3官方版
  3. MVC+ajax权限管理
  4. android中的通信机制总结
  5. Unity3D之Vector3.Dot和Vector3.Cross的使用
  6. C/C++技巧
  7. C#中的泛型详解
  8. Class类相关
  9. Android动画效果
  10. ysql+heartbeat+DRBD+LVS实现mysql高可用
  11. 下载并在Eclipse中关联Android源代码
  12. mac 修改系统配置参数 主机名 等
  13. QT添加exe文件的图标LOGO
  14. 在 .NET 4 中使用托管可扩展性框架构建可组合的应用程序
  15. RSA----实际函数库选择
  16. 内核中 EXPORT_SYMBOL 标志分析
  17. linux 用户密码过期时间
  18. windows系统nexus3安装和配置
  19. php RSA非对称加密 的实现
  20. tomcat8 manager页面限制IP访问

热门文章

  1. DECLARE_MESSAGE_MAP用法
  2. CH5E01[NOIP2010] 乌龟棋[暴力]
  3. 杂项之rabbitmq
  4. ECMAScript 2016(ES7) 知多少
  5. Azure基于角色的用户接入控制(RBAC)
  6. nginx错误
  7. 设置Nodejs NPM全局路径
  8. array_diff函数的注意事项
  9. hihoCoder#1139(二分+bfs)
  10. 杂项:DCloud.io