栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++运算符重载Mystring<,<=,>.>=,+,+=

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++运算符重载Mystring<,<=,>.>=,+,+=

小编犯的错误是:

1. 对象的指针比较大小,要使用strcmp(s1.ptr, s2.ptr);

2. +,+= 运算符重载时,内存需要创建新的空间,建议使用 ”换杯子“ 的方法进行

例题如下:

class MyString{
	char *ptr;
public:
	int size()const{
		return strlen(ptr);
	}
	MyString(){
		ptr=new char[1];
		ptr[0]='';
	}
	MyString(const char *p){
		ptr=new char[strlen(p)+1];
		strcpy(ptr,p);
	}
	MyString(const MyString &str){
		ptr=new char[str.size()+1];
		strcpy(ptr,str.ptr);
	}
	~MyString(){
		delete []ptr;
	}
	friend ostream & operator<<(ostream & out,const MyString &str); 
	friend MyString operator+(const MyString &s1,const MyString &s2); 
	friend int operator==(const MyString &s1,const MyString &s2);
	friend int operator!=(const MyString &s1,const MyString &s2);
	friend int operator<(const MyString &s1,const MyString &s2);
	friend int operator<=(const MyString &s1,const MyString &s2);
	friend int operator>(const MyString &s1,const MyString &s2);
	friend int operator>=(const MyString &s1,const MyString &s2);
	MyString & operator=(const MyString &s);
	MyString & operator+=(const MyString &s);
	char operator[](int i);
}; 


对该类重载教材233页表6-1中列出的那些运算符(这些运算符的含义和string类一致)。


main函数也写好了,请根据上面的类声明部分和main函数的内容,将未实现的运算符函数进行实现。main函数如下:

int main(){
	
	MyString s1("Hello"),s2("World"),s3("China");
	cout<<(s1>s2)<<" "<<(s1>=s2)<<" "<<(s1<=s2)<<" "<<(s2=0;i--)
		cout< 

正确解答如下:

#include
using namespace std;

ostream& operator<<(ostream& out,const MyString &str){
		out<(const MyString &s1,const MyString &s2){
		int jug5=strcmp(s1.ptr,s2.ptr);
		if(jug5>0) return 1;
		else return 0;//07
	}
	int operator>=(const MyString &s1,const MyString &s2){
		int jug6=strcmp(s1.ptr,s2.ptr);
		if(jug6>=0) return 1;
		else return 0;//08
	}
	MyString& MyString::operator=(const MyString &s){//no member functio//
		ptr=new char[s.size()+1];
		for(int i=0;isize()+1];
		 strcpy(tmp,ptr);//指针的比较、复制要用函数 
		 ptr= new char[this->size()+s.size()+1];
		 strcpy(ptr, tmp);
		 strcat(ptr, s.ptr);
		 delete[] tmp;
		 ptr[size()+s.size()+1] = '';
		 return *this;
	
	}
	char MyString::operator[](int i){
		//MyString s1;
		return ptr[i];//返回char类型指针 
	}

输出如下:

//输出如下
0 0 1 0
0 1
HelloWorld
China China China
HelloWorldChina
anihCdlroWolleH

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/923673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号