C++中String类的实现
2015-06-08 00:22
441 查看
#pragma once #include <iostream> #include <string.h> #define _SIZE_ 100 using namespace std; class Count { public: Count() :count(1){} void add() { count++; } void dec() { count--; } int getcount() { return count; } private: int count; }; class String { public: String(const char *s = "") { copy(ptr,s); } String(const String &s) { copy(ptr,s.ptr); counT.add(); } String& operator=(const String& s) { if (this != &s) { String tmp(s.ptr); char *temp = tmp.ptr; tmp.ptr = ptr; ptr = temp;//内存安全。 } return *this; } ~String() { if (counT.getcount() == 1) { cout << ptr << " :del" << endl; delete[]ptr; } } friend ostream& operator<<(ostream& os, String &s) { os << s.ptr; return os; } friend istream& operator>>(istream& is, String &s) { char buf[_SIZE_]; is >> buf; s.copy(s.ptr,buf); return is; } String& operator += (const String &s) { char *buf = new char[strlen(ptr) + strlen(s.ptr) + 1]; strcpy(buf, ptr); strcat(buf,s.ptr); copy(ptr,buf); return *this; } String& operator +=(const char *str) { char *buf = new char[strlen(ptr) + strlen(str) + 1]; strcpy(buf,ptr); strcat(buf,str); copy(ptr,buf); return *this; } bool operator != (const String &s) { return strcmp(ptr,s.ptr); } bool operator ==(const String &s) { return !strcmp(ptr,s.ptr); } private: void copy(char *&p,const char *s) { p = new char[strlen(s) + 1]; strcpy(p,s); } private: char *ptr; Count counT; };
#include <iostream> #include "String.h" using namespace std; int main() { String s("123"); String s1("456"); s += s1; return 0; }
“`
相关文章推荐
- C++求最大子数组之和
- C++ int与string的转化
- c语言变量和函数声明的修饰符static,extern,#define,const
- 一起学习C语言之建立链表
- C语言基础-语句、函数
- C语言中嵌入汇编语言实现简单的加法
- 【转】vc++6.0 字节定义和字节转换。
- LeetCode 3 Longest String
- LeetCodeOJ2 Add Two Sum
- LeetCodeOJ1 Two Sum
- C++中const加强
- C语言初学者编程规范—命名规则
- C++中const加强
- C++三目运算符的增强
- C++三目运算符的增强
- Visual C++学习笔记1:一定要注意ANSI和UNICODE的区别
- C++的一些感想
- C++ string学习
- C++中所有的变量和函数都必须有类型
- C++中所有的变量和函数都必须有类型