C++用字符数组实现MyString类

若不是考研复试我还不会拾起C++;

首先,MyString类仅有两数据成员(private):

char str[]字符数组;

int length长度;

然后,MyString类有三个构造函数:

默认构造函数:MyString();

带参数的构造函数:MyString(const char s[]);

拷贝构造函数:MyString(const MyString &s);

随后是析构函数:~MyString();

然后写两个成员函数,

一个设置内容的set_str(char s[]);一个获取MyString长度的get_length();

两个友元函数(运算符重载):

friend MyString operator+(const MyString &s1,const MyString &s2);

friend operator& operator<<(ostream os,const MyString &s);

因为VC++6.0的bug,我没有使用using namespace std;而是:

using std::endl;
using std::cout;
using std::ostream;


下面是实现代码:

#include<iostream>
#include<stdlib.h>

#define MAX 100

using std::endl;
using std::cout;
using std::ostream;

class MyString{
public:
	MyString();
	MyString(const char s[]);
	MyString(const MyString &s);
	~MyString();
	int get_length();
	void set_str(const char s[]);
	friend MyString operator+(const MyString &s1,const MyString &s2);
	friend ostream &operator<<(ostream &os,const MyString &s); 
private:
	char str[MAX];
	int length;
};

MyString::MyString(){
	this->length=0;
}

MyString::MyString(const char s[]){
	int i=0;
	while(s[i]!='\0'){
		this->str[i]=s[i];
		++i;
	}
	this->length=i;
}

MyString::MyString(const MyString &s){
	int i=0;
	while(s.str[i]!='\0'){
		this->str[i]=s.str[i];
		++i;
	}
	this->length=s.length;
}

MyString::~MyString(){
	length=0;
}

int MyString::get_length(){
	return this->length;
}

void MyString::set_str(const char s[]){
	int i=0;
	while(s[i]!='\0'){
		this->str[i]=s[i];
		++i;
	}
	this->length=i;
}
//友元函数不需要MyString::的修饰了;
MyString operator+(const MyString &s1,const MyString &s2){
	MyString str(s1);
	int i=0;
	int j=str.length;
	while(i<s2.length){
		str.str[j]=s2.str[i];
		++i;
		++j;
	}
	str.length=j;
	return str;
}

ostream &operator<<(ostream &os,const MyString &s){
	int i=0;
	while(i<s.length){
		cout<<s.str[i];
		i++;
	}
	return os;
}

void main(){
	MyString s1("Hello");
	MyString s2;
	s2.set_str("Hello");
	cout<<s2.get_length()<<endl;
	MyString s3;
	s3=s1+s2;
	cout<<s3.get_length()<<endl;
	cout<<s3<<endl;
}
个人第一篇博文,望支持!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值