(C++)重载运算符实验中的代码记录

重载运算符实验中的代码记录

实验题目要求:完成下列的 String 类,并在主函数 main( )中测试它。

class String {
	public:
		String(const char *str = NULL); // constructor
		String(const String &other);  // copy constructor
		~ String(void); // destructor
		String & operate =(char *str);
		String & operate =(const String &other);// 重载=运算符
		int operator==(String &other); // 重载==运算符
		int operator==(char *str);
	private:
		char *m_data; // used for storing the string
		int length;
};

实验要求分析:
本次的实验是实现重载=,==运算符,以及实现String类的构造函数,复制构造函数(确保深复制),析构函数。

实验代码补齐如下:

#include<iostream>
#include<cstring>
using namespace std;
class String {
	public:
		String(char *str = NULL); // constructor
		String(const String &other); // copy constructor
		~ String(void); // destructor
		String & operator =(char *str);
		String & operator =(const String &other);// 重载=运算符
		int operator==(String &other); // 重载==运算符
		int operator==(char *str);
	private:
		char *m_data; // used for storing the string
		int length;
};
String::String(char *str ) {
	if(str==NULL) {
		length=1;
	} else {
		length=strlen(str);
	}
	m_data=new char[length+1];
	if(str!=NULL)
		strcpy(m_data,str);
	m_data[length]='\0';
}
String::String(const String &other) {
	*this=other;
}
String::~ String(void) {
	delete[] m_data;
}
String& String::operator =(char *str) {
	length=strlen(str);
	m_data=new char[length+1];
	for(int i=0; i<=length; i++) {
		m_data[i]=str[i];
	}
	return *this;
}
String& String::operator=(const String &other) { // 重载=运算符
	m_data=new char[other.length+1];
	length=other.length;
	for(int i=0; i<other.length; i++) {
		m_data[i]=other.m_data[i];
	}
	m_data[length]=0;
	return *this;
}
int String::operator==(String &other) { // 重载==运算符
	if(length!=other.length)
		return 0;
	if(strcmp(m_data,other.m_data)!=0)
		return 0;
	return 1;
}
int String::operator==(char *str) {
	if(length!=strlen(str))
		return 0;
	for(int i=0; i<length; i++) {
		if(str[i]!=m_data[i])
			return 0;
	}
	return 1;
}

int main() {
	char ch1[10];
	char ch2[10];
	cout<<"请输入字符串ch1:";
	cin>>ch1;
	cout<<"请输入字符串ch2:";
	cin>>ch2;
	cout<<"现在将字符串ch1的值赋给string a"<<endl;
	String a(ch1);
	String b;
	cout<<"现在将string a 值赋给string b"<<endl;
	b=a;
	cout<<"a和b的匹配结果:";
	cout<<(a==b)<<endl;
	cout<<"a和ch2的匹配结果:";
	cout<<(a==ch2)<<endl;
	cout<<"现在将string b 值赋给string c"<<endl;
	String c(b);
	cout<<"c和ch1的匹配结果:";
	cout<<(c==ch1)<<endl;
}

实验的运行结果展示:

(1) 字符串1和字符串2不相等的情况

在这里插入图片描述

(2)字符串1和字符串2相等的情况

在这里插入图片描述

本次实验总结

运算符重载增强了程序的封装性,而且也增强了代码的可读性,当函数封装在类中后,主函数的调用利用数学思维就可以实现,不需要去管相关的具体代码实现。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值