为什么此操作员返回警告?

编程入门 行业动态 更新时间:2024-10-26 18:19:23
本文介绍了为什么此操作员返回警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么这个操作符++会返回警告?

Human& Human :: operator ++( int ){ Human temp(* this ); operator ++(); return temp; // 此处有警告。 }

警告是: 引用与本地变量'temp'关联的堆栈内存返回。 除了警告之外,结果没有问题。 这样做的正确方法是什么? 我正在学习超载。 我正在使用XCode 7.1.1 另一对增量工作没有警告。

人类&安培; Human :: operator ++(){ _health ++; _attack ++; _defense ++; 返回 * 此; }

解决方案

本地变量 temp 超出范围当函数返回并且之后不再有效时。 所以你应该在这里返回一个值而不是引用:

Human Human :: operator ++(int){人类临时(* this); operator ++(); 返回临时; }

参见此处en.cppreference/w/cpp/language/operator_incdec [ ^ ]表格下面的注释

Quote:

内置运算符的前缀版本返回引用和后缀版本返回值 I建议您在浏览器中将上述网站en.cppreference(或类似网站)加入书签。在尝试C ++功能时,这将非常有用。

Why this operator++ return a warning?

Human& Human::operator++(int){ Human temp(*this); operator++(); return temp; // warning here. }

The warning is: Reference to stack memory associated with local variable 'temp' returned. There was no problem with the result except for the warning though. What is the proper way to do it? I'm learning about overloading. I'm using XCode 7.1.1 another pair of the increment works without warning.

Human& Human::operator++(){ _health++ ; _attack++ ; _defense++; return *this; }

解决方案

The local variable temp goes out of scope when the function returns and is no longer valid afterwards. So you should return a value here rather a reference:

Human Human::operator++(int){ Human temp(*this); operator++(); return temp; }

[EDIT] See also here en.cppreference/w/cpp/language/operator_incdec[^] the Notes below the table:

Quote:

Prefix versions of the built-in operators return references and postfix versions return values

I suggest also to bookmark the above website en.cppreference (or a similar one) in your browser. It will be really helpful while trying out C++ features.

更多推荐

为什么此操作员返回警告?

本文发布于:2023-11-24 11:39:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625047.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!