c++在函数内部创建引用变量
c++ create reference variable inside function
假设我有以下函数:
void myFunc(P& first, P& last) {
std::cout << first.child.grandchild[2] << endl;
// ...
}
现在,让我们假设first.child.grandchild[2]
对于我的目的来说太长了。例如,假设它将频繁出现在myFunc(P&,P&)
内部的方程式中。所以,我想在函数中创建某种符号引用,这样我的方程就不会那么混乱了。我怎么能这么做?
特别是,请考虑下面的代码。我需要知道我可以插入什么语句,这样不仅line_1a的输出将始终与line_1b相同,而且line_2aine_2bvoid myFunc(P& first, P& last) {
// INSERT STATEMENT HERE TO DEFINE "g"
std::cout << first.child.grandchild[2] << endl; // line_1a
std::cout << g[2] << endl; // line_1b
g[4] = X; // where X is an in-scope object of matching type
std::cout << first.child.grandchild[4] << endl; // line_2a
std::cout << g[4] << endl; // line_2b
//...
}
假设grandchild
的类型为T
,大小为N
;下面是为数组创建引用的方法。
void myFunc(P& first, P& last) {
T (&g)[N] = first.child.grandchild;
...
}
我不喜欢这里的指针,尽管这也是一种可能的方式。因为,数组的静态大小有助于静态分析器进行范围检查。
如果你使用的是C++11编译器,那么auto
是最好的方法(@SethCarnegie已经提到):
auto &g = first.child.grandchild;
使用指针-然后可以在函数中更改它。
WhateverGrandchildIs *ptr=&first.child.grandchild[2];
std::cout << *ptr << std::endl;
ptr=&first.child.grandchild[4];
std::cout << *ptr << std::endl;
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++方法中的引用变量
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 使用更改此变量的函数在同一行中打印引用变量
- 将延迟变量分配给引用变量
- 如何通过引用获取引用变量的地址?
- 将引用变量传递给函数
- C++中引用变量的内存?
- 按名称存储和引用变量列表
- 返回一个C++引用变量 VS 返回一个变量
- c++ 在 if 语句中分配引用变量
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- C++ - 将一个变量分配给另一个变量和将变量分配给引用变量有什么区别?
- 在类范围内声明时,应在 C++14 中引用变量模板
- 当引用变量的引用"死亡"时,它会发生什么?
- 将非按引用变量分配给返回按引用的函数,反之亦然
- 引用变量如何存储在mem中
- 引用变量存储在哪里