读书人

运算符+重载解决方法

发布时间: 2012-03-05 11:54:01 作者: rapoo

运算符+重载
1我想重载运算符+,(如下),出错了。要怎么做。
2为什么重载运算符的参数要写成 RCInst& b(&代表什么)

#include<iostream.h>
#include<stdlib.h>
#include<string.h>
//const int CHAIN_NUM = 3;

class RCInst
{

public:
//char q[CHAIN_NUM];
char* ocname;
int ocNum;

RCInst()
{}
RCInst(char* a,int b)
{// ocname=new char[strlen(a)+1];
ocname=strdup(a);
ocNum=b;
cout<<"constructing "<<ocname<<endl;

}

RCInst(RCInst& a)
{ ocname=new char[strlen(a.ocname)+1];
strcpy(ocname,a.ocname);
ocNum=a.ocNum;
// ocname=strdup(a.ocname);
cout<<"copying "<<ocname<<endl;

}

~RCInst()
{
cout<<"destructing "<<ocname<<endl;
delete ocname;

}


/*
void operator++()
{
ocNum++;
}
*/

RCInst operator+(RCInst& b,RCInst& c)
{
int num=b.ocNum+c.ocNum;

char* ch=new[strlen(b.ocname)+strlen(c.ocname)];
ch=strcat(b.ocname,c.ocname);

RCInst z(ch,num);
return z;

}

};
void main()
{

//RCInst::RCInst_iterator a;
//a.show();

RCInst a("a",11);
cout<<"ocNum"<<a.ocNum<<endl;
RCInst b("b",21);
RCInst c;

c=a+b;
cout<<"c"<<c.ocNum<<endl;
}

[解决办法]

C/C++ code
    //重载不能去修改运算符本来的语意    //成员函数,只需要一个参数,形如    RCInst& operator+(const RCInst& b)    {    // 你用strlen(b.ocname)得到的只是指针变量的大小,四个字节,不是其指向的缓存的长度            } 

读书人网 >C++

热点推荐