复制构造函数
需求说明
- 自定义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