首页 新闻 会员 周边 捐助

这个类得实现应该如何修改

0
[已关闭问题] 关闭于 2012-02-22 22:25

// mystring.h -- class definition
#include <iostream>
#include
<string>
using namespace std;
class String
{
private:
char * str; // pointer to string
int len; // length of string
static int num_strings; // number of objects
static const int CINLIM = 80; // cin input limit
public:
// constructors and other methods
String(const char * s); // constructor
String(); // default constructor
String(const String &); // copy constructor
~String(); // destructor
int length () const { return len; }
// overloaded operator methods
String & operator=(const String &);
String
& operator=(const char *);
char & operator[](int i);
const char & operator[](int i) const;
// overloaded operator friends
friend bool operator<(const String &st, const String &st2);
friend
bool operator>(const String &st1, 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 function
static int HowMany();
};

// mystring.cpp -- String class methods

// 初始化静态类成员num_strings
int String::num_strings = 0;
// static method
int String::HowMany()
{
return num_strings;
}
// class methods,要求动态分配字符串内存空间
String::String(const char * s)
{
len
= strlen(s);
str
= new char[len];
str
= static_cast<char*>(s);
}
String::String()
{
len
= 4;
str
= new char[1];
str[
0] = '\0';
num_strings
++;
}
String::String(
const String & st)
{
*this(st.str);
}
String::
~String() // necessary destructor
{
delete str;
}
// overloaded operator methods
// assign a String to a String
String & String::operator=(const String & st)
{
if (this == &st)
return st;
delete [] str;
len
= st.len;
return st;
}
// assign a C string to a String
String & String::operator=(const char * s)
{
delete [] str;
len
= std::strlen(s);
str
= new char[len + 1];
std::strcpy(str, s);
return *this;
}
// read-write char access for non-const String
char & String::operator[](int i)
{
return str[i];
}
// read-only char access for const String
const char & String::operator[](int i) const
{
return static_cast<const char>(str[i]); //此处与上一空内容一样
}
// overloaded operator friends
bool operator<(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) < 0);
}
bool operator>(const String &st1, const String &st2)
{
return st2.str < st1.str;
}
bool operator==(const String &st1, const String &st2)
{
return st1.str == st2.str;
}
// simple String output
ostream & operator<<(ostream & os, const String & st)
{
os
<< st.str <<" " << st.len << " " << st.num_strings << std::endl;
}
// quick and dirty String input
istream & operator>>(istream & is, String & st)
{
is >> st.len >> st.str;
}
大家给修改下,源码有很多错误的地方

hailong的主页 hailong | 初学一级 | 园豆:70
提问于:2011-05-10 19:40
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册