西西河

主题:说说我前面提到过的面试题 -- 使用尽量中文

共:💬6 🌺4 新:
全看分页树展 · 主题 跟帖
家园 乱评一点答案

本着最小化俺的工作量的原则(猜测可能的需求引起工作量增加的事情俺不干,猜测错了要么干错了,要么白干):

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

全看分页树展 · 主题 跟帖


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河