首页 文章

为什么const变量不能通过引用传递?

提问于
浏览
1

我的讲义说

引用参数的参数必须是变量,而不是常量或表达式 .

因此

int f(double & var); // function prototype
...
const double t = 4.0;
int ret = f(t);

f(t) 是非法的 .

但我不明白,为什么 t 是非法的 . t 是一个常数,但仍然是一个变量,我不会通过引用传递 t .

3 回答

  • 4

    当你有一个引用参数时,传递的对象需要实际(至少能够)占用内存,常量(而不是const变量)则不需要 .

    I.E.以下是可以的:

    void foo(int & n) {
      n = 3;
    }
    void bar() {
      int i;
      foo(i);
      std::cout << "i is " << i << std::endl;
    }
    

    但如果你有:

    void qux() {
      foo(3);
    }
    

    在foo中赋值的赋值没有对象 .

    请注意,您可以将常量作为引用传递给const(即MyType const&),这是允许的,因为当引用是const时,赋值问题不存在 .

  • 1

    如果函数 f 修改 var 怎么办?如果 tconst ,那不应该发生 .

    这是 f 的示例实现:

    int f(double & var)
    {
        var += 1;
        return var;
    }
    

    这将改变作为参数传递的任何内容 . But 如果争论是 const ......运气不好 . 然后它是不允许的,编译器明确地告诉你这个 .

    这是编译器生成的错误:

    error: binding reference of type 'double&' to 'const double' discards qualifiers
    

    因此,通过将 const 变量传递给函数(没有非const参数),您将告诉编译器首先忽略变量的 const nss .

    如果您希望通过引用传递它,请通过 const -reference传递它:

    int f(const double & var)  //  or int f(double const& var)
    {
        var += 1;
        return var;
    }
    

    这告诉编译器保留其参数的常量 .

  • 0

    让我对答案加以评论:

    首先, t 不是常量,而是const变量 . 常数为4.0 . 你的讲义基本上是说你不能做一些像int ret = f(4.0);

    其次,你所看到的是类型不匹配 . const 作为限定符是该类型的一部分 . 你不能做以下事情:

    const int x = 1;
    int& ref_x = x;
    

    error:将类型'int&'绑定到'const int'的引用将丢弃限定符

    尽管如此,将 const 限定变量作为引用传递是合法的,要么使用const引用,要么抛弃const:

    • 使用const引用 const int& const_int_ref = x;

    • 使用const_cast: int& rx = const_cast<int&>(x);

    我更喜欢第一个 .

相关问题