DevC++重载赋值运算符后类型不匹配的问题

来源:百度知道 编辑:UC知道 时间:2024/06/29 01:10:56
请看下面的代码:
//代码开始
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class sample{
char *s;
public:
sample();
sample(const sample &ob);
~sample(){if(s) delete [] s; cout<<"Freeing s\n";}
void show(){cout<<s<<"\n";}
void set(char *str);
sample operator=(sample &ob);
};

sample::sample(){
s=new char('\0');
}

sample::sample(const sample &ob){
s=new char[strlen(ob.s)+1];
strcpy(s,ob.s);
}

void sample::set(char *str){
s=new char[strlen(str)+1];
strcpy(s,str);
}

sample sample::operator=(sample &ob){
if(strlen(ob.s)>strlen(s)){
delete [] s;
s=new char[strlen(ob.s)+1];
}

改成这样试试
sample sample::operator = (sample &ob)
{
delete []s;
s = new char [strlen(ob.s)+1];
strcpy(s,ob.s);
return *this;
}

ps:上面不对
改为这样sample sample::operator = (const sample &ob)
呵呵,大意了,参数为什么是const 引用就不多说了,那简直是必须的

VC++6.0编译通过

不过确实有个地方有点不妥,加个&试试?
sample &operator=(sample &ob);

= 需要你重载,不能直接用,sample是你自己定义的类,运算符要自己重载,直接用=是不行的

PS:这次是我错了,我没注意看代码,我只是给复制过去编译了一下。DEV C++是编译通过不了,你按照lcability说的改下试试。。

VC6编译正常能使用。
没有细看代码,不过可能是编译器问题……

PS:这位同学有自己写的重载啊

sample sample::operator=(sample &ob){
if(strlen(ob.s)>strlen(s)){
delete [] s;
s=new char[strlen(ob.s)+1];
}
strcpy(s,ob.s);
return *this;
}

暂时理解为编译器问题