- 程序有所改变。发帖如还有问题请报告
- 【征集】西西河的经济学,及清流措施,需要主动参与者,『稷下学宫』新认证方式,24年网站打算和努力目标
主题:说说我前面提到过的面试题 -- 使用尽量中文
本着最小化俺的工作量的原则(猜测可能的需求引起工作量增加的事情俺不干,猜测错了要么干错了,要么白干):
1.原题没指明何种平台和编译器,所以只用标准C++。(_MSC_VER,_mbslen之类的就不能用了)
2.原题没有要求处理不同字符类型,所以只支持char。
3.原题没说会从string派生子类,所以不要virtual dtor,耗内存更少。
#include <cstring>
#include <cassert>
#include <algorithm>
class string
{
public:
inline explicit string(const char* p=0, size_t len=0)
{ // if you know length, avoid strlen.
size_t length = p ? (len>0?len:(std::strlen(p))) : 0;
if( length>0 )
{
allocate(length);
std::memcpy(m_p, p, length+1);
}
else
{
m_p = 0;
m_len = 0;
}
}
inline string(const string& other) : m_len(0), m_p(0)
{
string s(other.m_p, other.m_len);
swap(s);
}
inline ~string()
{
delete []m_p;
}
inline string& operator=(const string& other)
{
string s(other);
swap(s);
return *this;
}
inline const string operator+(const string& other) const
{
string s(*this);
s+=other;
return s;
}
inline string& operator+=(const string& other)
{
if( other.m_len>0 )
{
string s;
size_t len = m_len + other.m_len;
s.allocate(len);
std::memcpy(s.m_p, m_p, m_len);
std::memcpy(s.m_p+m_len, other.m_p, other.m_len);
s.m_p[len] = '\0';
swap(s);
}
return *this;
}
inline void swap(string& other)
{
std::swap(m_len, other.m_len);
std::swap(m_p, other.m_p);
}
private:
// only for uninitialized or empty string.
// controlled use! m_p will not be a valid C-style string.
inline void allocate(size_t len)
{
assert(len>0);
m_p = new char[len+1];
m_len = len;
}
private:
size_t m_len;
char* m_p;
};
int main(int argc, char* argv[])
{
string s1("abcde"),s2("1234567"),s3;
s3=s1+s2; //now s3 should represent sth like "abcde1234567"
return 0;
}
修改: 所有函数加了inline
- 相关回复 上下关系6
🙂说说我前面提到过的面试题 4 使用尽量中文 字5436 2008-07-06 20:32:12
🙂乱评一点答案
🙂你这够复杂,面试的时候要写这么一个类,得花多少时间啊。 股市就是搏傻游 字0 2008-07-06 20:58:01
🙂其实如果熟练的话 使用尽量中文 字44 2008-07-06 21:03:52
🙂new分配内存失败是抛一个异常? 我记得当年好像也有返回NULL 股市就是搏傻游 字63 2008-07-06 21:25:34
🙂都有 使用尽量中文 字18 2008-07-06 21:31:57