幺幺捌 2020-04-22 20:19 采纳率: 33.3%
浏览 167
已采纳

为什么C++中operator =不加取址符会报错

#include <iostream.h>
#include <string>
class mystring{
    char * pstr;
    int length;
public:
    mystring(){
        pstr=NULL;
        length =0;}
    mystring(char * p,int n){
        pstr = new char[n];
        pstr= strcpy(p,pstr);
    }
    ~mystring(){delete[]pstr;}
    mystring  & operator = (const mystring & temp){
        if(pstr!=NULL)
            delete [] pstr;
        length=temp.length;
        pstr=new char[length+1];
        strcpy(pstr,temp.pstr);
        return *this;
    }
    friend ostream & operator<<(ostream & os,mystring & temp);
    friend istream & operator>>(istream & is,mystring & temp);
};

ostream & operator<<(ostream & os,mystring & temp){
    cout<<temp.pstr;
    return os;
}

istream & operator>>(istream & is,mystring & temp){
    char p[10000];
    if((temp.pstr)!=NULL)
        delete []temp.pstr;
    cout<<"请输入字符串内容:"<<endl;
    cin>>p;
    temp.pstr=new char[strlen(p)+1];
    strcpy(temp.pstr,p);
    temp.length=strlen(p);
    return is;
}

void main(){
    mystring a,b;
    cin>>a;
    b=a;
    cout<<"b="<<b<<endl;
}

有引用符不报错

有引用符不报错

没有引用符 报错了

没有引用符 报错了

  • 写回答

2条回答 默认 最新

  • threenewbee 2020-04-22 23:43
    关注

    不加也可以,但是你要正确实现拷贝构造函数。
    加上&,直接传引用,不需要调用拷贝构造函数。

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

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现