C ++编译器警告 - 返回局部变量 [英] C++ compiler warning - returning local variable

查看:108
本文介绍了C ++编译器警告 - 返回局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 引用本地变量'

tmp'returned

这是重载的代码

  const Int& Int :: operator +(const Int& p)const 
{
Int tmp = value + p.value;
return tmp;
}

以下是类

  class Int {
int value;
public:
Int(){} //默认构造函数
Int(int v):value(v){}
Int& operator =(const Int&);
const Int& operator +(const Int&)const;
};


解决方案

您不能返回对局部变量的引用。在运算符+()函数中,您正在创建一个局部变量 tmp 。一旦函数退出,它就会被销毁。



将函数的定义更改为:

p>

  const Int运算符+(const Int&)const; 

它会构建没有警告,也很好。


I'm simply trying to overload a + operator and I'm getting this compiler warning

reference to local variable 'tmp' returned

Here is the code for the overload

const Int& Int::operator+(const Int& p) const
{
    Int tmp = value + p.value;
    return tmp;
}

Here is the class

class Int{
    int value;
public:
    Int() {}    // default constructor
    Int(int v) : value(v) {}
    Int& operator=(const Int&);
    const Int& operator+(const Int&) const;
};

解决方案

You can't return a reference to a local variable. Inside the operator+() function, you're creating a local variable called tmp. It will get destroyed as soon as the function exits. You can't return a reference to that variable, because it no longer exists when the calling function gets the return value.

Change your definition of the function to:

const Int operator+(const Int&) const;

It would build without warnings and work fine too.

这篇关于C ++编译器警告 - 返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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