为什么这个操作符++会返回警告?
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.
更多推荐
为什么此操作员返回警告?
发布评论