C++拷贝构造函数和运算符重载(VC实现)

String.h文件:

#ifndef STRING_H
#define STRING_H

#include <ostream>
using namespace std;

class String
{
public:
	String(){ m_pStr = nullptr; }
	String(const char* pStr);
	String(const String& str);//拷贝构造函数
	~String()
	{
		if (m_pStr != nullptr)
		{
		 	delete m_pStr;
			m_pStr = nullptr;
		}
	}
	String& operator=(const String& str);//这里其实可以不返回对象的,但是表达式一般都具有返回值。
	String& operator=(const char* pStr);
	friend ostream& operator<<(ostream& output, const String& str);//只能将流运算符重载为友元函数,因为要返回流对象以供连续输出。
	int GetLength()
	{
		if (m_pStr == nullptr)
			return 0;
		else
			return strlen(m_pStr);
	}

private:
	char* m_pStr;
};

#endif

String.cpp文件:

#define _CRT_SECURE_NO_WARNINGS
#include "String.h"
#include <stdio.h>

String::String(const char* pStr)
{
	if (pStr != nullptr)
	{
		int len = strlen(pStr);
		m_pStr = new char[len + 1];
		m_pStr[len] = 0;
		strcpy(m_pStr, pStr);
	}
	else
		m_pStr = nullptr;
}

//拷贝构造函数,将对象作为参数或返回对象时都会调用
String::String(const String& str)
{
	if (str.m_pStr != nullptr)
	{
		char* pStr = str.m_pStr;
		int len = strlen(pStr);
		m_pStr = new char[len + 1];
		m_pStr[len] = 0;
		strcpy(m_pStr, pStr);
	}
	else
		m_pStr = nullptr;
}

String& String::operator = (const String& str)
{
	m_pStr = str.m_pStr;
	return *this;
}

String& String::operator=(const char* pStr)
{
	if (pStr != nullptr)
	{
		int len = strlen(pStr);
		m_pStr = new char[len + 1];
		m_pStr[len] = 0;
		strcpy(m_pStr, pStr);
	}
	else
		m_pStr = nullptr;
	return *this;
}

ostream& operator<<(ostream& output, const String& str)
{
	if (str.m_pStr != nullptr)
		printf("%s", str.m_pStr);
	return output;
}

测试文件(main.cpp):

#include <iostream>
using namespace std;

#include "String.h"

int main()
{
	String s1("Hello");
	cout << s1 << endl<<"你好啊"<<endl;
	String s2 = s1;//调用拷贝构造函数
	cout << s2 << endl;
	String s3;
	s3 = s1;//调用运算符重载函数
	cout << s3 << endl;
	String s4 = "haha";//调用了无参构造函数,而非调用=号运算符重载函数
	cout << s4 << endl;
	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/csdn_gddf102384398/article/details/84727640