C++ 类的几种基本方法
本文用例:
class CA { public: CA(); /// 默认构造函数 1 CA(const char *str=NULL); /// 带入参构造函数 2 CA(const CA &ca); /// 拷贝构造函数 3 ~CA(); /// 析构函数,唯一 4 CA &operater=(const CA &ca); /// 赋值运算符(=)重载 5 private: char *m_data; }
构造函数实现
1、默认构造函数
CA::CA(){}
2、带参数构造函数
CA::CA(const char *str) { if (str == NULL) { m_data = new char[1]; m_data[0] = '\0'; } else { m_data = new char[strlen(str) + 1]; strcpy(m_data,str); } }
3、拷贝构造函数
CA::CA(const CA ¶) { m_data = new char[strlen(para.m_data)+1]; stpcpy(m_data, para.m_data); }
4、析构函数
CA::~CA() { delete []m_data; }
5、运算符重载
CA &CA::operator=(const CA ¶) { if (this == ¶) { return *this; delete []m_data; /// 删除原数据,释放内存 m_data =new char[strlen(para.m_data) + 1]; strcpy(m_data,para.m_data); return *this; }
其他运算符可参考本例;

浙公网安备 33010602011771号