• 重载操作符号


    前几天一同学说去**面试,被问到现场写一个string类出来。

    要写出这个类,主要知道几个默认构造函数,这个也是面试中常考的。

    第一:拷贝构造函数。string(const string &lhs);

    第二:赋值构造函数。string & operator=(const string &lhs)

    //这里就有2个问题

    第一:赋值构造函数为什么是返回string &//这里是一个引用。

    第二,operator=(const string &lhs)这里为啥只有一个参数。

    对于第一个问题。我们知道,=(赋值)操作符,在c++语言在的意义是 a=b。

    就是b赋值给a。所以,当你构造好这个对象之后,事实上,返回的就是这个对象了,当然是引用了。

    第二个问题,为啥只有一个参数呢。

    如果operator=操作符是类的成员变量,事实上,他有一个隐藏的函数参数,就是this了。

    ==============

    string.cpp:40: error: `String& operator=(const String&, const String&)' must be a nonstatic member function

    //尝试将operator=放到类外面时候,报了这个错。

    1 #include<stdio.h>
    2 #include<string.h>
    3  class String
    4 {
    5 String(const char *p = NULL)
    6 {
    7 if(NULL != p)
    8 {
    9 int strLen = strlen(p);
    10 pStr = new char[strLen + 1];
    11 strncpy(pStr,p,sizeof(pStr));
    12 }
    13 else
    14 {
    15 pStr = new char[1];
    16 pStr[0] = 0;
    17 }
    18 }
    19 String(const String &rhs)
    20 {
    21 int strLen = strlen(rhs.pStr);
    22 pStr = new char[strLen + 1];
    23 strncpy(pStr,rhs.pStr,sizeof(pStr));
    24 }
    25 String & operator= (const String &rhs)
    26 {
    27 if(this == &rhs)
    28 return *this;
    29 delete [] pStr;
    30 int strLen = strlen(rhs.pStr);
    31 pStr = new char[strLen + 1];
    32 strncpy(pStr,rhs.pStr,sizeof(pStr));
    33 return *this;
    34 }
    35 public:
    36 char *pStr;
    37 };
     
  • 相关阅读:
    lua 10 迭代器
    lua 9 parttern 字符极其简要的介绍
    lua 7 运算符
    lua 6 函数
    lua 5 流程控制 if
    线程池的设计问题/线程数量计算
    一个父子进程管道通信的复习
    redis 网络库文件 重构
    带标准IO带缓存区和非标准IO 遇到fork是的情况分析
    libevent 同性恋 讲解
  • 原文地址:https://www.cnblogs.com/xloogson/p/2096763.html
Copyright © 2020-2023  润新知