| #ifndef WRONG_H_ #define WRONG_H_ class Wrong { private: char * str; //存储数据 int len; //字符串长度 public: Wrong(const char * s); //构造函数 Wrong(); // 默认构造函数 ~Wrong(); // 析构函数 friend ostream & operator<<(ostream & os,const Wrong& st); }; #endif Wrong.cpp: #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() { 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; } test_right.cpp: #include <iostream> #include <stdlib.h> #include "Wrong.h" using namespace std; int main() { Wrong temp("天极网"); cout<<temp<<'\n'; system("PAUSE"); return 0; } |
| #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<<endl; cout<<test2<<endl; cout<<test3<<endl; Wrong* wrong1=new Wrong(test1); cout<<*wrong1<<endl; delete wrong1; cout<<test1<<endl;//在Dev-cpp上没有任何反应。 cout<<"使用正确的函数:"<<endl; show_right(test2); cout<<test2<<endl; cout<<"使用错误的函数:"<<endl; show_wrong(test2); cout<<test2<<endl;//这一段代码出现严重的错误! Wrong wrong2(test3); cout<<"wrong2: "<<wrong2<<endl; Wrong wrong3; wrong3=test4; cout<<"wrong3: "<<wrong3<<endl; cout<<"下面,程序结束,析构函数将被调用。"<<endl; return 0; } void show_right(const Wrong& a) { cout<<a<<endl; } void show_wrong(const Wrong a) { cout<<a<<endl; } |
关注此文的读者还看过: