C++_进阶篇_3

复制构造函数

需求说明

  • 自定义String(字符串)类,以简化字符串的操作
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    String.h
#pragma once
#include <iostream>
#include <cstring>


using namespace std;

//自定义的字符串包装类
class String
{
private:
	int m_length;  //字符串的实际长度 -不包括\0
	char * m_value; //实际存储字符的字符数组

public:
	String();
	String(const char * str);//必须要加上const
	~String();	

	//重载
	const String & operator=(const String & str);
	friend ostream & operator<<(ostream & out, const String & str);
};

String.cpp

#include "pch.h"
#include "MyString.h"


String::String() : m_length(0)//默认长度=0
{
	this->m_value = new char[m_length + 1];
	this->m_value[0] = '\0';
}

String::String(const char * str)
{
	//将传入的字符串str的值赋给当前对象中的m_value
	if (str == NULL)
	{
		this->m_value = new char[m_length + 1];
		this->m_value[0] = '\0';
		return;
	}
	m_length = strlen(str); //获得要复制字符串的长度
	m_value = new char[m_length + 1]; //为\0留出一个空间
	strcpy_s(m_value, m_length + 1, str); //vs2005之后可能存在错误,需要在c++预处理器项加_CRT_SECURE_NO_WARNINGS保存即可
}

const String & String::operator=(const String & str)
{
	delete[] m_value;
	m_length = str.m_length;
	m_value = new char[m_length + 1];
	strcpy_s(m_value, m_length + 1, str.m_value);
	return *this;
}


ostream & operator<<(ostream & out, const String & str)
{
	out << str.m_value << "\n";
	//out << "m_value的长度 " << str.m_length;
	printf("%p", str.m_value);
	return out;
}


String::~String()
{
	//析构时,释放字符数组所指向的空间
	delete[] m_value;
}

main.cpp

// c++_learning_5.30.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include "integer.h"
#include "MyString.h"

void TestString();

int main()
{
	TestString();

	return 0;
}

void TestString()
{
	String str1("这里是中文");
	String str2 = "adafda";
	cout << str1 << endl;
	cout << str2 << endl;
	cout << "对象之间的赋值:" << endl;
	str1 = str2;
	cout << str1 << endl;
	cout << str2 << endl;
}

结果

这里是中文
00570DB0
adafda
00570B80
对象之间的赋值:
adafda
00570A30
adafda
00570B80
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值