0

我试图了解如果在返回函数时添加 const 或忽略它有什么不同。让我通过一个例子来解释我的问题。

const int foo()
{
    return 3;
}

int main()
{
    int check;
    check=foo();
    cout<<"before:"<<check<<endl;
    check=1;
    cout<<"after:"<<check<<endl;
    return 0;   
}

到目前为止,我一直认为,由于我编写了 const foo() 我无法更改检查变量,但是我编译它并没有出错。

我想知道在我的 foo() 函数之前写 const 会得到什么或失去什么。

提前致谢

4

4 回答 4

2

你没有改变变量。您正在更改它的副本。

check=foo();

foo分配to返回的值checkcheck不是const

于 2013-10-25T07:52:48.907 回答
2

原始返回类型的const修饰符将被忽略。

另请参阅此问题:我应该返回 const 对象吗?

于 2013-10-25T07:54:13.937 回答
0

不同之处在于编译器警告:

warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
const int foo()
              ^

现场演示

这种东西被忽略了,所以没有效果。

于 2013-10-25T07:52:36.477 回答
0

当您尝试返回参考时,它会有所不同。

例如:

int gGlobal;

const int & func()
{
    return gGlobal;
}

int main ()
{
     //Following statement will give error.
     func() = 3;
     return 0;
}
于 2013-10-25T08:01:53.400 回答