zoukankan      html  css  js  c++  java
  • 赋值运算符函数

    题目:如下为类型CMyString的声明,请为该类型添加赋值运算符函数。

    1 class CMyString
    2 {
    3 public:
    4 CMyString(char *pData=NULL);//构造函数
    5 CMyString(const CMyString& str);//拷贝构造函数
    6 ~CMyString();//析构函数
    7 private:
    8 char* m_pData;//数据域,字符指针
    9 };

    关注如下几点:是否把返回值类型声明为该类型的引用,并在函数结束前返回实例的自身引用。是否把传入的参数的类型声明为常量引用。是否释放实例自身的内存。是否判断传入的参数和当前的实例是不是同一个实例。

     1 #include "stdafx.h"
     2 #include<string>
     3 class CMyString
     4 {
     5 public:
     6     CMyString(char* pData =  NULL);
     7     CMyString(const CMyString& str);
     8     ~CMyString(void);
     9 
    10     CMyString& operator = (const CMyString& str);
    11 
    12     void Print();
    13 private:
    14     char* m_pData;
    15 };
    16 
    17 CMyString::CMyString(char* pData)
    18 {
    19     if(pData == NULL)
    20     {
    21         m_pData = new char[1];
    22         m_pData[0] = '';
    23     }
    24     else
    25     {
    26         int length = strlen(pData);
    27         m_pData = new char[length + 1];
    28         strcpy(m_pData, pData);
    29     }
    30 }
    31 
    32 CMyString::CMyString(const CMyString &str)
    33 {
    34     int length = strlen(str.m_pData);
    35     m_pData = new char[length + 1];
    36     strcpy(m_pData, str.m_pData);
    37 }
    38 
    39 CMyString::~CMyString()
    40 {
    41     delete[] m_pData;
    42 }
    43 
    44 CMyString& CMyString::operator = (const CMyString& str)
    45 {
    46     if(this == &str)
    47         return *this;
    48 
    49     delete []m_pData;
    50     m_pData = NULL;
    51 
    52     m_pData = new char[strlen(str.m_pData) + 1];
    53     strcpy(m_pData, str.m_pData);
    54 
    55     return *this;
    56 }
    57 
    58 void CMyString::Print()
    59 {
    60     printf("%s
    ", m_pData);
    61 }
    62 
    63 int main()
    64 {
    65     char* text = "Hello world";
    66     CMyString str1(text);
    67     CMyString str2;
    68     str2 = str1;
    69 
    70     printf("The expected result is: %s.
    ", text);
    71 
    72     printf("The actual result is: ");
    73     str2.Print();
    74     
    75     return 0;
    76 }

  • 相关阅读:
    PHP.ini配置
    Ubuntu下启动/重启/停止apache服务器
    为 Ubuntu 上的 PHP 安装 APC,提升应用速度
    PHP文件上传并解决中文文件名乱码问题
    php目录结构
    PHP 服务器变量 $_SERVER
    PHP 编程的 5 个良好习惯
    PHP导入Excel和导出数据为Excel文件
    SharePoint 计算列公式(拷贝微软的SDK)
    SharePoint2010 文档评分(转)
  • 原文地址:https://www.cnblogs.com/sankexin/p/5643324.html
Copyright © 2011-2022 走看看