zoukankan      html  css  js  c++  java
  • 指针类成员变量

    当类中包括指针类成员变量时,一定要重载其拷贝构造函数、赋值函数和析构函数,这既是对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; }
  • 相关阅读:
    安装SQL Server 2012遇到“需要更新的以前的Visual Studio 2010实例.”
    搭建网站 discuzx ecshop php
    appserv安装
    php 修改 AppServ 下Apache 端口
    sed基本用法
    grep命令
    awk命令详解二
    Java面向对象六大原则
    Java基础——常用类之日期时间类
    springMVC第一天——入门、整合与参数绑定
  • 原文地址:https://www.cnblogs.com/blogXiong/p/3322743.html
Copyright © 2011-2022 走看看