帮忙看看!谢谢了
//strquote.cpp -- different designs#include <iostream>
#include <string>
using namespace std;
string version1(const string & s1,const string & s2);
const string & version2(string & s1,const string & s2); //has side effect
const string & version3(string & s1,const string & s2); //bad design
int main()
{
string input;
string copy;
string result;
cout<<"Enter a string: ";
getline(cin,input);
copy=input;
cout<<"Your string as entered: "<<input<<endl;
result=version1(input,"***");
cout<<"Your string enhanced: "<<result<<endl;
cout<<"Your original string: "<<input<<endl;
result=version2(input,"###");
cout<<"Your string enhanced: "<<result<<endl;
cout<<"Your original string: "<<input<<endl;
cout<<"Resetting original string.\n";
input=copy;
result=version3(input,"@@@");
cout<<"Your string enhanced: "<<result<<endl;
cout<<"Your original string: "<<input<<endl;
system("pause");
return 0;
}
string version1(const string & s1,const string &s2)
{
string temp;
temp=s2+s1+s2;;
return temp;
}
const string & version2(string & s1,const string & s2)
{
s1=s2+s1+s2;
return s1;
}
const string & version3(string & s1,const string & s2) //这个函数的错误在哪里?
{ //书上说存在一个致命的错误:返回一个指向version3()中声明的变量的引用.具体的说,
//问题是由于下面的复制语句引发的:result=version3(input,"@@@");程序试图引用已经
//释放的内存
//不明白????高手能详细解释一下吗?
string temp;
temp=s2+s1+s2;;
return temp;
}
[[it] 本帖最后由 tymstill 于 2008-4-17 16:31 编辑 [/it]]