头文件声明类
string1.h
#pragma once
#include<iostream>
using namespace std;
class String
{
private:
char* str;
int len;
static int num_strings;
public:
static const int CINLIM = 80;
public:
//构造和析构
String(const char*);// 构造函数
String();//默认构造函数
String(const String&);//拷贝构造函数
~String();//析构函数
//运算符重载
String& operator=(const String&);
String& operator=(const char*);
char& operator[](int i);
const char& operator[](int i)const;
//运算符重载友元
friend bool operator<(const String& st, const String& st2);
friend bool operator>(const String& st, const String& st2);
friend bool operator==(const String& st, const String& st2);
friend ostream & operator<<(ostream& os, const String& st);
friend istream& operator>>(istream& is, String& st);
//静态函数
static int HowMany();
};
源文件实现类
string.cpp
#define _CRT_SECURE_NO_WARNINGS
#include"string1.h"
#include<cstring>
using namespace std;
//初始化静态成员变量
int String::num_strings = 0;
//静态成员函数定义
int String::HowMany()
{
return num_strings;
}
//构造和析构
String::String(const char* s)//构造函数
{
len = strlen(s);
str = new char[len + 1];
str = strcpy(str, s);
num_strings++;
}
String::String()//默认构造
{
len = 7;
str = new char[len + 1];
strcpy(str, "default");
num_strings++;
}
String::String(const String& s)//拷贝构造
{
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
num_strings++;
}
String::~String()//析构函数
{
num_strings--;
delete[] str;
}
//运算符重载
String& String::operator=(const String& st)
{
if (this == &st)
return *this;
delete[] str;
len = st.len;
str = new char[len + 1];
strcpy(str, st.str);
return *this;
}
String& String::operator=(const char* s)
{
delete[] str;
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
return *this;
}
char& String::operator[](int i)
{
return str[i];
}
const char& String::operator[](int i)const
{
return str[i];
}
//运算符重载友元
bool operator<(const String& st, const String& st2)
{
return (strcmp(st.str, st2.str) < 0);
}
bool operator>(const String& st, const String& st2)
{
return st2 < st;
}
bool operator==(const String& st, const String& st2)
{
return (strcmp(st.str, st2.str) == 0);
}
ostream& operator<<(ostream& os, const String& st)
{
os << st.str;
return os;
}
istream& operator>>(istream& is, String& st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
st = temp;
//while (is && is.get() != '\0')
//continue;
return is;
}
测试
#include<iostream>
#include"string1.h"
using namespace std;
int main() {
String name = "Mick";//"="运算符
cout << "name: " << name << endl;//"<<"运算符
String name2("Tom");//一般构造创建对象
if (name < name2)//"<"运算符
cout << name << "<" << name2 << endl;
String name3 = String(name);//拷贝构造创建对象
if (name == name3)//"=="运算符
cout << name << "==" << name3 << endl;
cout << "name[2]: " << name[2] << endl;//"[]"运算符
String name4 = String();//默认构造创建对象
cout << "name4: " << name4 << endl;
String name5;
cout << "请输入字符串:";
cin >> name5;
cout << "name5: " << name5 << endl;
cout << "调用静态成员函数:" << String::HowMany() << endl;
}
运行结果