码迷,mamicode.com
首页 > 其他好文 > 详细

运算符重载(二)

时间:2016-09-02 11:18:22      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

    String类:

技术分享

一 []运算符的重载

    []运算符的使用可能有以下几种情况:

String s1="asdfdsf";
const String s2="abcd";

char A=s1[2]; //1
s1[2]=a; //2

char B=s2[2];  //3
s2[2]=b;  //4

对于1和2的情况,需要重载:

char& operator[](unsigned int index);

返回引用是为了可以实现情况2。

    对于const String,3允许但4不允许,所以要返回const string&

char& String::operator[](unsigned int index)
{
    //return str_[index];
    //non const 版本调用 const版本
    return const_cast<char&>(static_cast<const String&>(*this)[index]);//先把*this转换成从const,调用const函数,在去掉const属性
}
const char& String::operator[](unsigned int index) const
{
    return str_[index];
}

二 +运算符的重载

String s3 = "xxx";
String s4 = "yyy";

String s5 = s3 + s4; //1
String s6 = "zzz" + s4;  //2

    为了允许情况2,+运算符需要重载为友元,同时还要有一个转换构造函数配合:

friend oprator+(const String& s1, const String& s2);

 但是不允许+两侧都是非对象类型。

String String::(const String& s1, cosnt String& s2)
{
    int len = strlen(s1.str_) + strlen(s2.str_) + 1;
    char* newstr = new char[len];
    memset(newstr, 0, len);
    strcpy(newstr, s1.str_);
    strcat(newstr, s2.str_);

    String tmp(newstr);
    delete newstr;
    return tmp;
}

三 <<运算符

friend ostream& operator<<(ostream& os, cosnt String& s);

 

运算符重载(二)

标签:

原文地址:http://www.cnblogs.com/lulu10922/p/5832491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!