类string的构造函数、拷贝构造函数和析构函数
来源:互联网 发布:环境破坏的资料数据 编辑:程序博客网 时间:2024/06/06 03:34
可用于探究 c++ 语言的一些特性:RVO,格式化,可变参数列表,等等,很好的试验原材料
引用http://www.cppblog.com/life02/archive/2011/03/07/96085.html 在这个帖子的基础上稍微添加修改了点内容。
String 类的原型如下
class String
{
public:
String(const char *str=NULL); //构造函数
String(const String &other); //拷贝构造函数
~String(void); //析构函数
String& operator=(const String &other); //等号操作符重载
ShowString();
private:
char *m_data; //指针
};
String::~String()
{
delete [] m_data; //析构函数,释放地址空间
}
String::String(const char *str)
{
if (str==NULL)//当初始化串不存在的时候,为m_data申请一个空间存放'\0';
{
m_data=new char[1];
*m_data='\0';
}
else//当初始化串存在的时候,为m_data申请同样大小的空间存放该串;
{
int length=strlen(str);
m_data=new char[length+1];
strcpy(m_data,str);
}
}
String::String(const String &other)//拷贝构造函数,功能与构造函数类似。
{
int length=strlen(other.m_data);
m_data=new [length+1];
strcpy(m_data,other.m_data);
}
String& String::operator =(const String &other)
{
if (this==&other)//当地址相同时,直接返回;
return *this;
delete [] m_data;//当地址不相同时,删除原来申请的空间,重新开始构造;
int length= strlen (other.m_data);
m_data=new [length+1];
strcpy(m_data,other.m_data);
return *this;
}
String::ShowString()//由于m_data是私有成员,对象只能通过public成员函数来访问;
{
cout<<this->m_data<<endl;
}
main()
{
String AD;
char * p="ABCDE";
String B(p);
AD.ShowString();
AD=B;
AD.ShowString();
}
1. strCopy 函数可以为标准库函数 char *strcpy(char *dest, const char *src);
需要#inculde <string.h>
2.参考连接:
高质量C++C编程指南 http://man.chinaunix.net/develop/c&c++/c/c.htm
字符串函数 http://www.ggv.com.cn/forum/clib/string/strcpy.html
- string类的构造函数,析构函数,拷贝构造函数和赋值构造函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- String类的构造函数,析构函数,拷贝构造函数和赋值函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- 编写类String的构造函数、拷贝构造函数、析构函数和赋值函数
- string类的构造函数、析构函数、拷贝构造函数和赋值函数
- 编写类String 的构造函数、拷贝构造函数、析构函数和赋值函数
- 写String类的普通构造函数,析构函数,拷贝构造函数和赋值函数
- 编写类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类String的构造函数拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- C++面试之 类string的构造函数、拷贝构造函数和析构函数
- 网易游戏笔试题:编写string类的构造函数、拷贝构造函数、赋值构造函数和析构函数
- String的构造函数,拷贝构造函数、析构函数和赋值函数
- VS配置属性
- 【UIKit-125-3】#import <UIKit/UIViewController.h>
- MySQL学习笔记20150925时间数据类型以及字符集与varchar(M)M最大值关系
- 【软考之路】-数据结构
- BZOJ 3997: [TJOI2015]组合数学
- 类string的构造函数、拷贝构造函数和析构函数
- NSObject的描述(+description)方法和对象的描述(-description)方法,NSLog默认输出的修改(后知后觉)
- Objective-C 基础知识之 (十四):属性 Property 点语法
- 自学QT之鼠标事件
- 第九周第五天
- UVa 460 - Overlapping Rectangles
- 培训第三天
- hdu1162
- Codeforces Beta Round #3——B. Lorry