若不是考研复试我还不会拾起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;
}
个人第一篇博文,望支持!