zoukankan      html  css  js  c++  java
  • 重载操作符号

    前几天一同学说去**面试,被问到现场写一个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 };
     
  • 相关阅读:
    一个有趣的.net程序死锁问题
    腾讯2013年实习生笔试题目(附答案)
    C#函数式程序设计初探基础理论篇
    IE的BUG?
    OpenPetra 以及CentOS Mono 3.0 部署包
    自己封装的内存缓存类DotNet.Caches.Bytecached
    Windows Azure Services安装及故障排查
    接口
    利用SQL Server的扩展属性自动生成数据字典
    CentOS配置ssh无密码登录的注意点
  • 原文地址:https://www.cnblogs.com/xloogson/p/2096763.html
Copyright © 2011-2022 走看看