各位好!小弟有一个问题想请教,还请各位多多指教一下!是关于c++问题.
#include <iostream.h> #include <string.h> #include <stdlib.h> class sample{ char *s; public: sample(); sample(const sample &ob); ~sample(){if(s) delete []s; cout<<"Freeing s\n";} void show() {cout<<s<<"\n";} sample operator =(sample &ob); void set(char *s); };
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]; } strcpy(s,ob.s);
return *this; }
sample input() //此函数在创建临时对象(调用复制构造函数)后,调用一次析构函数,当 { 临时对象附给ob对象(调用重载运算符)后销毁,调用一次析构函数. char instr[80]; 整个程序结束时,ob被销毁,调用一次析构函数,总共3次,可为什么 sample str; 结果是4次呢?! cout<<"Enter a string:\n"; cin>>instr; str.set(instr);
return str; }
int main() { sample ob;
ob=input(); ob.show();
return 0; }
我想结果应是输出3个"Freeing s",可是输出了4个,小弟百思不得其解,还望解释一下!
谢谢!!