幺幺捌 2020-04-20 18:49 采纳率: 33.3%
浏览 448

C++中为什么运算符重载要加取址符

先上代码

#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<<"请输入字符串内容:"< 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;
}

![图片说明](https://img-ask.csdn.net/upload/202004/22/1587557151_182844.png)


有取址符不报错


![图片说明](https://img-ask.csdn.net/upload/202004/22/1587557177_469077.png)

没有取址符,报错了

我想问各位大佬,为什么没有取址符这里报错了
  • 写回答

1条回答 默认 最新

  • threenewbee 2020-04-20 20:54
    关注

    这是引用,不是取地址。目的是避免调用拷贝构造函数
    好比 int a = b * c;这里的*不是指针。

    评论

报告相同问题?

悬赏问题

  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?