【问题标题】:would sending a const to a function that gets a non const param be considered an error?将 const 发送到获取非 const 参数的函数是否会被视为错误?
【发布时间】:2021-07-27 09:29:10
【问题描述】:

假设我们有这个功能

void  something(int a)
{}

在主函数中我们这样做

int main()
{
 const int a=7;
something(a);
}

这会被视为错误吗?

【问题讨论】:

  • 请记住,参数是通过 value 传递的。这意味着如果main 变量a 被复制 到something 参数变量a 中的值。所以简而言之,你显示的内容很好,不会导致任何错误。
  • @Someprogrammerdude 好吧,如果它是通过引用传递的,那会有所不同吗?
  • 是的,这是一个错误。如果一个函数想要一个非常量类型是因为它想要改变值。如果你传递一个 const,你就不能改变它。
  • 非 const 引用不能绑定到 const 变量。所以是的,那么它应该会导致构建错误。
  • .... 算上所说的,问题是,你要修改a吗?

标签: c++ constants


【解决方案1】:

没有。

当您调用函数时,会制作参数的副本:

 const int x = 0;
 something(x);

类似

 const int x = 0;
 int y = x;          // completely fine, no error

此外,考虑到当您通过值传递时,在参数上使用const 仅在函数内部起作用:

void  something(const int a)
{
    a = 42; // error, a is const
}

虽然函数的类型实际上是void(int),即参数上的const是一个实现细节。


通过引用传递确实很重要:

 void foo(int& x); // <- modifies parameter

 const int x;
 foo(x);           // error, because x cannot be modified

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多