在 c++ 中使用引用
Use of references in c++
我试图围绕引用的使用。到目前为止,我已经明白引用必须是常量,它们就像变量的别名。但是,在为堆栈编写代码时,当我通过引用推送函数传递值时。我必须包括"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中使用所谓的右值引用(&&)。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?