面试题中,C++的基础编程题占很大一块,下面做个总结:
【string类实现】 包括 构造函数、拷贝构造、析构函数、 拷贝赋值及C风格转换c_str()方法
#include
#include
using namespace std;
class String {
public:
String (const char* str = NULL) :
m_str (strcpy (new char[strlen (str ? str : "") + 1],
str ? str : "")) {}
String (const String& that) :
m_str (strcpy (new char[strlen (that.m_str) + 1],that.m_str)) {}
~String (void) {
if (m_str) {
delete[] m_str;
m_str = NULL;
}
}
String& operator= (const String& that) {
if (&that != this) {
/*
delete[] m_str;
m_str = strcpy (new char[strlen (
that.m_str) + 1], that.m_str);
*/
/*
char* str = new char[strlen (that.m_str) + 1];
delete[] m_str;
m_str = strcpy (str, that.m_str);
*/
String str (that);
swap (m_str, str.m_str);
}
return *this;
}
const char* c_str (void) const {
return m_str;
}
private:
char* m_str;
};
int main (void) {
String s1 ("Hello, world !");
cout << s1.c_str () << endl;
String s2 (s1);
cout << s2.c_str () << endl;
String s3 ("Hello, String !");
cout << s3.c_str () << endl;
s3 = s2;
cout << s3.c_str () << endl;
return 0;
}