猿问
下载APP

请问该如何定义并实现string类的函数?

定义并实现string类的函数


HUX布斯
浏览 78回答 3
3回答

春华秋衣

#include <string.h>class string{public:string();string(const char *s);string(const string& s);~string();//&nbsp;赋值运算符const string & operator =(const char *s);const string & operator =(const string &s);// 比较字符串是否相等bool operator == (const char *s) const;bool operator == (const string &s) const;// 比较字符串大小bool operator < (const char *s) const;bool operator < (const string &s) const;bool operator > (const char *s) const;bool operator > (const string &s) const;// 字符串长度int length() const { return m_length; }// 转化到字符指针const char * data() const { return m_data; }// 清空字符串void clear();private:int m_length;char *m_data;};string::string(): m_length(0){m_data = new char[1];m_data[0] = '\0';}

DIEA

#include <string.h>class string{public:string();string(const char *s);string(const string& s);~string();//&nbsp;赋值运算符const string & operator =(const char *s);const string & operator =(const string &s);// 比较字符串是否相等bool operator == (const char *s) const;bool operator == (const string &s) const;// 比较字符串大小bool operator < (const char *s) const;bool operator < (const string &s) const;bool operator > (const char *s) const;bool operator > (const string &s) const;// 字符串长度int length() const { return m_length; }// 转化到字符指针const char * data() const { return m_data; }// 清空字符串void clear();private:int m_length;char *m_data;};string::string(): m_length(0){m_data = new char[1];m_data[0] = '\0';}string::string(const char *s){m_length = strlen(s);m_data = new char[m_length+1];memcpy(m_data, s, m_length+1);}string::string(const string &s){m_length = s.length();m_data = new char[m_length+1];memcpy(m_data, s.data(), m_length+1);}string::~string(){clear();}void string::clear(){m_length = 0;if (m_data)delete [] m_data;m_data = NULL;}const string & string::operator =(const char *s){clear();m_length = strlen(s);m_data = new char[m_length+1];memcpy(m_data, s, m_length+1);return *this;}const string & string::operator =(const string &s){clear();m_length = s.length();m_data = new char[m_length+1];memcpy(m_data, s.data(), m_length+1);return *this;}bool string::operator == (const char *s) const{return strcmp(m_data, s) == 0;}bool string::operator == (const string &s) const{return m_length == s.length() && strcmp(m_data, s.data()) == 0;}bool string::operator < (const char *s) const{return strcmp(m_data, s) < 0;}bool string::operator < (const string &s) const{return strcmp(m_data, s.data()) < 0;}bool string::operator > (const char *s) const{return strcmp(m_data, s) < 0;}bool string::operator > (const string &s) const{return strcmp(m_data, s.data()) < 0;}

海绵宝宝撒

1.接口主体只限于对方法,索引器以及属性的声明; 2.接口成员是隐式公开的,和C 里的抽象类里的纯虚函数是相同的。不能被实例化。 定义接口的关键字
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答