I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  15 随笔 :: 339 文章 :: 128 评论 :: 146万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

已知类String的原型为:

复制代码
class String
{
public:
    String(
const char *str = NULL);
    String(
const String &other);
    
~String(void);
    String 
& operate = (const String &other);
private:
    
char *m_data;
};
复制代码


编写String的上述四个函数:

(1) String的析构函数

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


(2) String的构造函数

复制代码
String::String(const char *str)
{
    
if(str == NULL)
    {
        m_data 
= new char[1];
        
*m_data = '\0';
    }
    
else
    {
        
int length = strlen(str);
        m_data 
= new char[length + 1];
        strcpy(m_data, str);
    }
}
复制代码


(3) String的拷贝构造函数

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


(4) String的赋值函数

复制代码
String & String::operate = (const String &other)
{
    
if(this == &other)
        
return *this;

    delete []m_data;

    
int length = strlen(other.m_data);
    m_data 
= new char[length + 1];
    strcpy(m_data, other.m_data);

    
return *this;
}
复制代码


调用实例:
1. 调用构造函数:String s("hello");
2. 调用拷贝构造函数:String s1("hello");   String s2 = s1;
3. 调用赋值函数:String s1("hello");   String s2;   s2 = s1;

 

posted on   jcsu  阅读(457)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示