在 c++ 中使用引用

Use of references in c++

本文关键字:引用 c++      更新时间:2023-10-16

我试图围绕引用的使用。到目前为止,我已经明白引用必须是常量,它们就像变量的别名。但是,在为堆栈编写代码时,当我通过引用推送函数传递值时。我必须包括"const"关键字。我需要知道为什么这是必要的。

简而言之,为什么这有效

class stack
{
public:
    void push(const int &x);
};
void stack::push(const int &x)
{
    // some code for push
}
 int main()
 {
    stack y;
    y.push(12);
    return 0;
 }

但这没有?

class stack
{
public:
    void push(int &x);
};
 void stack::push(int &x)
 {
     // some code for push
 }
int main()
{
    stack y;
    y.push(12);
    return 0;
}

如果您使用

int main()
{
    stack y;
    int X = 12;
    y.push(X);
    return 0;
}

即使您删除"常量",您也会看到它有效。这是因为 12 是常数,但 X 不是常数!

换句话说:

  • 如果您使用void push(const int &x); ---则可以使用常量或非常量值!
  • 如果您使用void push(int &x); ---则只能使用非常量值!

基本规则是:

  • 我的函数不需要更改参数的值:使用 void push(const int &x);
  • 我的函数需要更改参数的值:使用 void push(int &x); [请注意,如果您打算更改参数的值,当然它不能是常量 12,而是值为 12 的某个变量,这就是区别!

使用 rvalue(文字 12)调用推送方法。在C++中,右值只能使用常量引用参数调用,或者在C++11中使用所谓的右值引用(&&)。