类的构造函数,析构函数,赋值函数

来源:互联网 发布:yy语音 mac 编辑:程序博客网 时间:2024/06/17 07:56
// 提示strcpy安全问题,解决方法#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <stdint.h>using namespace std;class MyClass{public:MyClass();~MyClass();void foo(){cout << "A" << endl;}private:};MyClass::MyClass(){}inline MyClass::~MyClass()// 析构函数可以是内联函数{cout << "inline destructed." << endl;}class StringT{public:StringT(const char *str = NULL);           // 普通构造函数StringT(const StringT &other);             // 拷贝构造函数StringT & operator=(const StringT &other); // 赋值函数void Print(const StringT &other) const;    // const成员函数~StringT(void);                            // 析构函数private:char *m_pdata;};StringT::~StringT(void){delete m_pdata;}void StringT::Print(const StringT &other) const{int len = strlen(other.m_pdata);char *p = other.m_pdata;for (int i = 0; i < len; i++){cout << *(p++);}cout << endl;}StringT::StringT(const char *str){if (str == NULL){m_pdata = new char[1];*m_pdata = '\0';} else{int length = strlen(str);m_pdata = new char[length + 1];strcpy(m_pdata,str);}}StringT::StringT(const StringT & other){if (other.m_pdata == NULL){m_pdata = new char[1];*m_pdata = '\0';} else{int length = strlen(other.m_pdata);m_pdata = new char[length + 1];strcpy(m_pdata,other.m_pdata);}}//赋值函数实现方法①StringT& StringT::operator =(const StringT &other){// 1检测是否自身赋值if (this == &other){return *this;}// 2释放原有内存资源delete m_pdata;// 3重新分配内存资源,并赋值other中内容int length = strlen(other.m_pdata);m_pdata = new char[length + 1];strcpy(m_pdata, other.m_pdata);return *this;}//赋值函数实现方法② 源自剑指offer面试例题1//StringT& StringT::operator =(const StringT &other)//{//if (this != &other)//{//StringT strTmp(other);//char *pTmp = strTmp.m_pdata;//strTmp.m_pdata = m_pdata;//m_pdata = pTmp;//}//return *this;//}int main(){MyClass *P = new MyClass();P->foo();delete P;StringT str("hello");StringT s(str);StringT t = s;cout << "str = ";str.Print(str);cout << "s = ";s.Print(s);cout << "t = ";t.Print(t);return 0;}

0 0
原创粉丝点击