65,211
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
#include <string>
using namespace std;
#ifndef WRONG_H_
#define WRONG_H_
class wrong
{
public:
char *str;
wrong(const char *s);
wrong(const wrong& a);
wrong& operator=(const wrong& a);
wrong();
~wrong();
friend ostream& operator < <(ostream &os,const wrong &st);
private:
//char *str;
int len;
};
#endif
#include <iostream>
#include <cstring>
#include "wrong.h"
using namespace std;
wrong::wrong(const char * s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}//拷贝数据
wrong::wrong(const wrong& a)
{
len=a.len;
str=new char(len+1);
strcpy(str,a.str);
}
wrong& wrong::operator=(const wrong& a)
{
if(this==&a)
return *this;
delete [] str;
len=a.len;
str=new char[len+1];
strcpy(str,a.str);
return *this;
}
wrong::wrong()
{
len =0;
str = new char[len+1];
str[0]='\0';
}
wrong::~wrong()
{
cout < <"这个字符串将被删除:" < <str < <'\n';//为了方便观察结果,特留此行代码。
delete [] str;
}
ostream & operator < <(ostream & os, const wrong & st)
{
os < < st.str;
return os;
}
#include <iostream>
#include <stdlib.h>
#include "wrong.h"
using namespace std;
void show_right(const wrong&);
void show_wrong(const wrong);
int main()
{
wrong test1("第一个范例。");
wrong test2("第二个范例。");
wrong test3("第三个范例。");
wrong test4("第四个范例。");
cout < <"下面分别输入三个范例:\n";
cout < <test1.str < <endl;
cout < <test2.str < <endl;
cout < <test3.str < <endl;
wrong* wrong1=new wrong(test1);//为什么不能用wrong* wrong1=new wrong;wrong1=test1;?
cout < <wrong1->str < <endl;
delete wrong1;
cout < <test1.str < <endl;//这句有错了吗?怎么没有反映了?
cout < <"使用正确的函数:" < <endl;
show_right(test2);
cout < <test2.str < <endl;//这里我的理解反而应该是错误的才对,因为在函数调用的时候,并没有调用复制构造函数
//所以在函数调用完成以后就会释放对象所指向的内容,此处应该出现野指针!等待高手
//帮我指点迷津了,谢谢!
cout < <"使用错误的函数:" < <endl;
show_wrong(test2);
cout < <test2.str < <endl; //这里我理解应该是正确的,
wrong wrong2(test3);
cout < <"wrong2: " < <wrong2.str < <endl;
wrong wrong3;
wrong3=test4;
cout < <"wrong3: " < <wrong3.str < <endl;
cout < <"下面,程序结束,析构函数将被调用。" < <endl;
return 0;
}
void show_right(const wrong& a)
{
cout < <a.str < <endl;
}
void show_wrong(const wrong a)
{
cout < <a.str < <endl;
}