指针类成员变量

 

当类中包括指针类成员变量时,一定要重载其拷贝构造函数、赋值函数和析构函数,这既是对C++程序员的基本要求。

 

编写String类的构造函数、析构函数和赋值函数

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

class String
{
public:
     String(const char *str = NULL);
     String(const String &other);
     String & operator =(const String &other);
     ~ String(void);

     char* c_str() const;
private:
     char *m_data;
};


String::String(const char *str)
{
       m_data = strcpy(new char[strlen(str?str:"")  + 1], str?str:"");
}

char* String::c_str() const
{
    return m_data;
}

String::~String(void)
{
    if(m_data)
    {
        delete [] m_data;
    }
}

String::String(const String &other)
{
    m_data = strcpy(new char[strlen(other.c_str())+1], other.c_str());
}


String & String::operator =(const String &other)
{
    if(&other != this)
    {
        /*代码复用*/
        String str(other);
        /*swap(other.c_str(), this->c_str());
      没有重载swap(char*, char*)供调用*/ char* temp = other.c_str(); strcpy(other.c_str(), c_str()); strcpy(c_str(), temp); } return *this; } int main() { String str1("hello!"); String str2(str1); String str3 = str2; cout<<str1.c_str()<<endl<<str2.c_str()<<endl<<str3.c_str()<<endl; return 0; }

 

 

 

 

转载于:https://www.cnblogs.com/blogXiong/p/3322743.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值