结构体的构造、拷贝、赋值、析构和字符串的拷贝、构造、赋值和析构函数的比较
来源:互联网 发布:淘宝刷几单封号 编辑:程序博客网 时间:2024/05/16 11:39
最近学习突然发现结构体也可以像字符串一样实现拷贝构造那些,然后比较了一下,下面是结构体和字符串的构造、拷贝、赋值和析构函数代码解释:
struct Node{ char *name; int age; // 构造函数 Node(char *n = 0, int a = 0){ name = strdup(n.name); age = a; } // 拷贝构造 Node(const Node& n){ name = strdup(n.name); age = n.age; } // 赋值函数 Node& operator=(const Node& n){ if(this != &n) { if(name != 0) free(name); name = strdup(n.name); age = n.age; } return *this; } // 析构函数 ~Node(){ if(name != 0) free(name); }};
字符串原型
class String { public: String(const char *str = NULL); // 普通构造函数 String(const String &other); // 拷贝构造函数 ~ String(void); // 析构函数 String & operate =(const String &other); // 赋值函数 private: char *m_data; // 用于保存字符串 }; //构造函数 Sting::String(const char *str = NULL){ if(NULL == str) { 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(const String &other){ int length =strlen(other.m_data); m_data =new char[length+1]; strcpy(m_data,other.m_data);}//赋值函数String & operate =(const String &other){ if(this == other) return *this; else { detele[]m_data; int length = strlen(other.m_data); m_data = new char[length+1]; strcpy(m_data,other.m_data); return *this; }}//析构函数~ String(void){ detele[]m_data;}
阅读全文
0 0
- 结构体的构造、拷贝、赋值、析构和字符串的拷贝、构造、赋值和析构函数的比较
- string类的构造函数,析构函数,拷贝构造函数和赋值构造函数
- C++之析构函数/拷贝构造函数/拷贝赋值函数的概念和使用
- String的构造函数,拷贝构造函数、析构函数和赋值函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- String类的构造函数,析构函数,拷贝构造函数和赋值函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- 编写类String的构造函数、拷贝构造函数、析构函数和赋值函数
- string类的构造函数、析构函数、拷贝构造函数和赋值函数
- 编写类String 的构造函数、拷贝构造函数、析构函数和赋值函数
- 写String类的普通构造函数,析构函数,拷贝构造函数和赋值函数
- 类的构造函数、拷贝构造函数、赋值运算符和析构函数
- 字符串的构造函数、析构函数、拷贝构造函数、赋值操作符
- 网易游戏笔试题:编写string类的构造函数、拷贝构造函数、赋值构造函数和析构函数
- 对象的生灭——构造函数、拷贝构造函数、赋值构造函数和析构函数
- 拷贝构造函数和赋值构造函数的异同
- 拷贝构造函数和赋值构造函数的异同
- 拷贝构造函数和赋值构造函数的异同
- mysql 性能分析及explain用法——数据库优化
- 一篇就够了系列之Service全解析
- QT5的软键盘输入法实现
- Xposed插件开发(一)简单demo
- git clone 指定分支操作
- 结构体的构造、拷贝、赋值、析构和字符串的拷贝、构造、赋值和析构函数的比较
- PHP实现定时任务的五种方法
- 006
- 自己做了个网站 网址:http://www.sunshinelin.club
- 适配器模式与外观模式
- Maven 学习资料整理
- Apache Hive
- tomcat启动端口被占用4445
- 人生如茶,空杯以对