为什么此操作员返回警告? [英] Why this operator returns warning?

查看:115
本文介绍了为什么此操作员返回警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



 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 ++();
返回临时;
}







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

Quote:

内置运算符的前缀版本返回引用和后缀版本返回值

I建议您在浏览器中将上述网站en.cppreference.com(或类似网站)加入书签。在尝试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 http://en.cppreference.com/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.com (or a similar one) in your browser. It will be really helpful while trying out C++ features.


这篇关于为什么此操作员返回警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆