C++中string类的实现

    面试题中,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;
}

    
    
   
   

        该代码出自一个10+年编程老鸟之手,极尽简洁高效之能。构造函数中用初始化列表初始化成员变量m_str,虽然对于普通数据类型,别无二致,但是对于类类型来说,最好使用初始化列表,为什么呢?由下面的测试可知,使用初始化列表少了一次调用默认构造函数的过程,这对于数据密集型的类来说,是非常高效的。
顺带一提除了性能问题之外,有些时场合初始化列表是不可或缺的,以下几种情况时必须使用初始化列表
1. 常量成员,因为常量只能初始化不能赋值,所以必须放在初始化列表里面
2. 引用类型,引用必须在定义的时候初始化,并且不能重新赋值,所以也要写在初始化列表里面
3. 没有 默认构造函数 的类类型,因为使用初始化列表可以不必调用默认构造函数来初始化,而是直接调用拷贝构造函数初始化

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值