C++实现string的极少部分功能

实现构造、拷贝构造、析构、赋值以及输出操作
String.h

#ifndef _String_//防卫式声明
#define _String_
#pragma warning(disable : 4996)//忽略4996警告
#include<iostream>
using namespace std;
class String
{
public:
	String(const char* s=0);//构造,一定要加上const,才能使常量字符进行初始化
	String(const String& s);//拷贝构造
	String& operator=(const String& s);//重载赋值操作
	~String();//析构
private:
	char* str;

	friend ostream& operator<<(ostream& os, const String& s);//友元
};
ostream& operator<<(ostream& os, const String& s);//重载输出
#endif _String_

String.cpp

#include "String.h"
String::String(const char* s)
{
	if (s)
	{
		this->str = new char[strlen(s) + 1];
		strcpy(this->str, s);
	}
	else
	{
		this->str = new char[1];
		*this->str = '\0';
	}
}

String::String(const String& s)//声明和定义处只能一处有默认参数
{
	this->str = new char[strlen(s.str) + 1];
	strcpy(this->str, s.str);
}

String& String::operator=(const String& s)
{
	if (this == &s)//自身赋给自身直接返回(必须)
	{
		return *this;
	}
	delete[]this->str;//先释放已有空间
	this->str = new char[strlen(s.str) + 1];//重新开辟空间
	strcpy(this->str, s.str);
	return *this;
}

String::~String()
{
	delete[]str;
}

ostream& operator<<(ostream& os, const String& s)//只能写为全局函数
{
	return (os << s.str);
}

测试.cpp

#include"String.h"
int main()
{
	String s;
	String s1("hello,world");
	cout << s1 << endl;
	s = s1;
	cout << s << endl;
	String s3(s1);
	cout << s3;
}

含有指针的类基本上需要实现拷贝构造函数、赋值函数以及析构函数(three tree)
array new 要对应array delete

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值