C++达到String分类
2015-09-13 21:00
453 查看
这是一个非常经典的面试题,能够测试学生很短的时间C++法师是综合,答案应包含C++大多数知识类,保证书String符类可以完成值、抄、的变量和其它函数的定义。
#include<iostream> using namespace std; class String { public: String(const char *str=NULL); String(const String &other); ~String(void); String &operator =(const String &other); private: char *m_data; }; String::String(const char *str) { cout<<"构造函数被调用了"<<endl; if(str==NULL)//避免出现野指针,如String b;假设没有这句话。就会出现野 //指针 { m_data=new char[1]; *m_data=''/0''; } else { int length=strlen(str); m_data=new char[length+1]; strcpy(m_data,str); } } String::~String(void) { delete m_data; cout<<"析构函数被调用了"<<endl; } String::String(const String &other) { cout<<"赋值构造函被调用了"<<endl; int length=strlen(other.m_data); m_data=new char[length+1]; strcpy(m_data,other.m_data); } String &String::operator=(const String &other) { cout<<"赋值函数被调用了"<<endl; if(this==&other)//自己拷贝自己就不用拷贝了 return *this; delete m_data;//删除被赋值对象中指针变量指向的前一个内存空间,避免 //内存泄漏 int length=strlen(other.m_data);//计算长度 m_data=new char[length+1];//申请空间 strcpy(m_data,other.m_data);//拷贝 return *this; } void main() { String b;//调用构造函数 String a("Hello");//调用构造函数 String c("World");//调用构造函数 String d=a;//调用赋值构造函数。由于是在d对象建立的过程中用a来初始化 d=c;//重载的赋值函数调用后, }
相关文章推荐
- C语言漫谈(二)
- 「C语言回顾之旅」第二篇:指针详解进阶
- C++指针和动态内存分配
- 网易游戏2016校招"数据挖掘研究员"在线比赛题一求解算法(C++)
- C++中的指针和数组
- Effective C++——条款36(第6章)
- C++Primer Plus 第九章-存储持续性、作用域和链接性
- 【C/C++学院】0802-链式栈/链表队列以及优先队列/封装链表库
- C++派生类的继承方式总结:
- C++中的 cout 和cin
- map的详细用法
- map容器对象插入数据的4种方式讲解
- C++中的static关键字的总结
- 【LeetCode从零单刷】Valid Anagram
- c++一些常用函数的积累
- c++一些常用函数的积累
- 12个有趣的C语言面试题及答案
- c++求数组长度
- C语言之数组专题:数组指针、指针数组、数组做函数参数退化、数组名、数组类型
- C++虚函数