重载运算符什么时候用引用返回值的问题

img


这个重载运算符+的位置
CStr operator+(const CStr &cn) 为什么这里返回值为什么不用&啊


#include "CNString.h"
//重载运算符:=
CNString& CNString::operator=(const CNString &cn)
{
    this->m_s = new char[strlen(cn.m_s)+1];
    strcpy(this->m_s,cn.m_s);
    return *this;
}
//重载运算符:+
CNString CNString::operator+(const CNString &cn)//为什么这里不用&呢
{
    CNString temp;
    temp.m_s = new char[strlen(this->m_s)+strlen(cn.m_s)+1];
    strcpy(temp.m_s, this->m_s);
    strcat(temp.m_s, cn.m_s);
    return temp;
}
//重载运算符:[]
char CNString::operator[](int index)
{
    if(index >= strlen(this->m_s))
    {
        return '\0';
    }
    return this->m_s[index];
}
//重载运算符:<
bool CNString::operator<(const CNString &cn)
{
    if(strcmp(this->m_s, cn.m_s) < 0)
    {
        return true;
    }
    return false;
}
//重载运算符:>
bool CNString::operator>(const CNString &cn)
{
    if(strcmp(this->m_s, cn.m_s) > 0)
    {
        return true;
    }
    return false;
}
//重载运算符:==
bool CNString::operator==(const CNString &cn)
{
    if(strcmp(this->m_s, cn.m_s) == 0)
    {
        return true;
    }
    return false;
}
//默认构造函数
CNString::CNString()
{
    this->m_s = new char('\0');
}
//构造函数
CNString::CNString(const char *s) {
    m_s = new char[strlen(s)+1];
    strcpy(m_s, s);
}
//拷贝构造函数
CNString::CNString(const CNString &c)
{
    m_s = new char[strlen(c.m_s)+1];
    strcpy(m_s,c.m_s);
}
//析构函数
CNString::~CNString()
{
    delete m_s;
    m_s = nullptr;
}
//输出数据
void CNString::display()
{
    std::cout << m_s << std::endl;
}

这看你是返回*this,还是重新定义一个新对象,return新对象

operator+(const T& rh)
如果返回引用,则必须返回*this;或者返回rh,那么你在+里面的修改将影响这两个操作数,与逻辑不符
例如 int a=5,b=3;
c=a+b;结束后a或者b的值发生变化合理吗?

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632