更多C++学习经验,从《C++ Primer》入手学习C++
能够准确无误地编写出String类的构造函数、拷贝构造函数、赋值函数和析构函数的面试者至少已经具备了C++基本功的60%以上!
编写类String的构造函数、析构函数和赋值函数,已知类String的原型为:
class MString
{
public:
MString(const char *str = NULL); // 普通构造函数
MString(const MString &other); // 拷贝构造函数
~MString(void); // 析构函数
MString & operator =(const MString &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
实现代码:
#include "stdafx.h"
#include "MString.h"
#include "string.h"
#pragma warning(disable:4996)
MString::MString(const char* str)
{
if (str == nullptr)
{
// 得分点:对空字符串自动申请存放结束标志'\0'的空
m_data = new char[1];
m_data[0] = '\0';
}
else {
int len = strlen(str);
m_data = new char[len + 1];
strcpy(m_data, str);
}
}
MString::~MString()
{
delete[] m_data;
m_data = nullptr;
}
// 得分点:输入参数为const型
//拷贝构造函数
MString::MString(const MString &other)
{
int len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
}
//赋值函数
MString& MString::operator=(const MString &other)//得分点,const参数类型
{
//得分点
if (this == &other)
{
return *this;
}
//得分点
delete[] m_data;
m_data = nullptr;
int len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
return *this;
}
当类中包括指针类成员变量时,一定要重载其拷贝构造函数、析构函数和赋值函数,这既是对C++程序员的基本要求,也是《Effective C++》中特别强调的条款。