C++中赋值函数,拷贝函数的简单应用
来源:互联网 发布:淘宝整点抢购软件 编辑:程序博客网 时间:2024/05/16 17:11
#include<iostream>
#include<cstring>
using namespace std;
class String{
public:
//构造函数
String(const char* str){
if (str == NULL){
m_str = new char[1];
m_str = '\0';
}
else{
m_str = new char[strlen(str) + 1];
strcpy(m_str, str);
}
//m_str = new char[strlen(str ? str : "") + 1];
//strcpy(m_str, str ? str : "");
}
//析构函数
~String(){
if (m_str){
delete[] m_str;
m_str = NULL;
}
}
//拷贝构造函数
String(const String& that){
m_str = new char[strlen(that.m_str) + 1];
strcpy(m_str, that.m_str);
}
//赋值函数
String&operator = (const String& that){
if (&that != this){
//小鸟版本
/*delete[] m_str;
m_str = new char[strlen(that.m_str) + 1];
strcpy(m_str, that.m_str);*/
//大鸟版本
/* char*str = new char[strlen(that.m_str) + 1];
delete[] m_str;
m_str = strcpy(str,that.m_str);*/
//老鸟版本
String temp(that);
swap(m_str, temp.m_str); //交换两个值
}
return *this;
}
const char* c_str(void)const{
return m_str;
}
private:
char* m_str;
};
int main(){
String s1("hello, world");
cout << s1.c_str() << endl;
String s2 = s1;//拷贝
cout << s2.c_str()<<endl;
String s3("hello,linux");
cout << s3.c_str() << endl;
s3 = s1;//赋值
cout << s3.c_str() << endl;
return 0;
}
- C++中赋值函数,拷贝函数的简单应用
- 浅谈c/c++中类的拷贝构造函数和重载赋值函数
- 【C++】拷贝构造函数和赋值函数
- C++ 的构造/析构/赋值/拷贝函数比…
- 类的拷贝构造函数、赋值函数
- 【C/C++】拷贝构造函数和赋值函数
- 拷贝,赋值构造函数赋值
- String类中构造函数、拷贝构造函数、赋值函数的实现
- C++中构造函数,拷贝构造函数和赋值函数的区别和实现
- 对构造函数、拷贝构造函数和赋值操作符调用的简单回顾
- 对构造函数、拷贝构造函数和赋值操作符调用的简单回顾
- 【C++】拷贝构造函数和赋值符函数
- c++_7: 拷贝构造函数和赋值构造函数
- C ++ 拷贝构造函数和赋值构造函数 非常经典
- 赋值函数、拷贝构造函数
- 拷贝构造函数赋值函数
- 拷贝构造函数,赋值函数
- C++中拷贝构造函数与拷贝赋值操作符
- this在方法赋值过程中无法保持(隐式丢失)
- 信息的表示和处理
- python3 实现延迟计算
- NumPy学习笔记(1)--NumPy库简介
- 使用Oracle SQL Developer连接数据库中遇到的一系列错误
- C++中赋值函数,拷贝函数的简单应用
- [JAVA基础汇总]Java 多线程编程
- 算法训练 水仙花
- jquery中attr() & prop() 的区别与其实现方法
- Python基础之re模块
- TCP/IP协议三次握手与四次握手流程解析
- 机器学习中的训练集、验证集和测试集
- 蓝桥杯取球博弈
- 配置对象方法传参