类方法用字符串实现运算符的重载

运算符的重载:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。

本代码实现的成员函数有构造函数、拷贝构造函数、=运算符、+运算符(类内实现对象加对象,对象加字符串,类外实现字符串加对象)、析构函数、<运算符、!=运算符、[ ]运算符、<<输出符(类外实现)。

两个类外实现的函数用了友元函数,类内由于有this指针,形参省略左面的,类外没有this指针,所以形参都不可省略。

由于版本问题,用#pragma warning(disable:4996);屏蔽不安全的提示。

代码如下:

#include<iostream>
#include<string>
using namespace std;

#pragma warning(disable:4996);
class String
{
public:
	String(char* str)
	{
		mptr = new char[strlen(str) + 1]();
		strcpy_s(mptr, strlen(str) + 1, str);
	}
	String(const String& rhs)
	{
		mptr = new char[strlen(rhs.mptr) + 1]();
		strcpy_s(mptr, strlen(rhs.mptr) + 1, rhs.mptr);
	}
	String& operator=(const String& rhs)
	{
		if (this != &rhs)
		{
			delete[] mptr;
			mptr = new char[strlen(rhs.mptr) + 1]();
			strcpy_s(mptr, strlen(rhs.mptr) + 1, rhs.mptr);
		}
		return *this;
	}
	const String operator+(const String& rhs)
	{
		int len = strlen(mptr) + strlen(rhs.mptr) + 1;
		char* temp = new char[len]();
		strcpy_s(temp, strlen(mptr) + 1, mptr);
		strcat(temp, rhs.mptr);
		String tmp(temp);
		delete[] temp;
		return tmp;
	}
	const String operator+(char* rhs)
	{
		int len = strlen(mptr) + strlen(rhs) + 1;
		char* temp = new char[len]();
		strcpy_s(temp, strlen(mptr) + 1, mptr);
		strcat(temp, rhs);
		String tmp(temp);
		delete[] temp;
		return tmp;
	}
	~String()
	{
		delete[] mptr;
		mptr = NULL;
	}
	bool operator<(const String& rhs)
	{
		return strcmp(mptr, rhs.mptr) < 0;//int  -1  0  1
	}
	bool operator!=(const String& rhs)
	{
		return !(strcmp(mptr, rhs.mptr) == 0);
	}
	char& operator[](int index)
	{
		return mptr[index];
	}

private:
	char* mptr;
	friend const String operator+(char*, const String&);
	friend std::ostream& operator<<(std::ostream&, const String&);
};

const String operator+(char* lhs, const String& rhs)
{
	int len = strlen(lhs) + strlen(rhs.mptr) + 1;
	char* temp = new char[len]();
	strcpy_s(temp, strlen(lhs) + 1, lhs);
	strcat(temp, rhs.mptr);
	String tmp(temp);
	delete[] temp;
	return tmp;
}
std::ostream& operator<<(std::ostream& out, const String& rhs)
{
	out << rhs.mptr;
	return out;
}
int main()
{
	String str1("hello");
	String str2 = "world";
	String str3 = str1 + str2;
	str3 = str1 + "hi";
	str3 = "hi" + str2;

	if (str1 < str2)
	{
		std::cout << str1 << std::endl;
	}
	if (str1 != str2)
	{
		std::cout << str2 << std::endl;
	}
	char a = str1[0];
	std::cout << a << std::endl;
	return 0;
}
发布了27 篇原创文章 · 获赞 8 · 访问量 1522

猜你喜欢

转载自blog.csdn.net/qq_43824618/article/details/102751284
今日推荐