_Phoebe__ 2022-03-30 16:16 采纳率: 96.9%
浏览 137
已结题

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

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;
}
  • 写回答

3条回答 默认 最新

  • CSDN专家-link 2022-03-30 16:26
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月7日
  • 已采纳回答 3月30日
  • 创建了问题 3月30日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改