快捷导航

引用用于类对象,为什么运行会崩溃

#include #include using namespace std;const string & version3(string & s1, const string & s2); // bad designint main(){ string input; string copy; string result; cout

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员1

main 函数缺了尾大括号,不过应该是贴代码时落下了吧。


在 version3 中,你返回的是函数中的变量 temp。这个 temp 的作用域仅在函数之中,在函数运行结束后 temp 会被销毁,这样返回的这个引用就引用无效对象了。


在函数返回引用时一定要注意不要返回函数的 local 变量。
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP