本文只实现String类的构造函数、析构函数、赋值构造函数和赋值函数,其他操作不再详述,一般的笔试面试基本上也只会要求实现这四个函数的功能。
#include <iostream>
using namespace std;
class String {
public:
// 构造函数
String(const char *str=NULL);
// 拷贝构造函数
String(const String& other);
// 赋值函数
String& operator =(const String &other);
// 析构函数
~String(void);
private:
char *data;
};
String::String(const char * str) {
if (str == NULL)
{
data = new char[1];
*data = '\0';
}
else {
int len = strlen(str) + 1;
data = new char[len];
strcpy(data, str);
}
}
String::String(const String& other) {
int len = strlen(other.data) + 1;
data = new char[len];
strcpy(data, other.data);
}
String & String::operator=(const String& other) {
// 判断是不是自赋值
if (this == &other)
return *this;
delete[]data;
int len = strlen(other.data) + 1;
data = new char[len];
strcpy(data, other.data);
// 返回本对象的引用
return *this;
}
String::~String() {
delete[]data;
}
原文链接: https://www.cnblogs.com/maluning/p/8961854.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/272977
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!