c++在函数内部创建引用变量

c++ create reference variable inside function

本文关键字:引用 变量 创建 内部 函数 c++      更新时间:2023-10-16

假设我有以下函数:

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_2b

void 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;