2

假设我有以下功能:

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_2a 的输出始终与line_2b输出相同。换句话说,我不想要 的值的副本first.child.grandchild,而是到对象的引用或符号链接first.child.grandchild

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
    //...
}    
4

2 回答 2

1

使用指针 - 然后您可以在函数中更改它。

WhateverGrandchildIs *ptr=&first.child.grandchild[2];

std::cout << *ptr << std::endl; 

ptr=&first.child.grandchild[4];

std::cout << *ptr << std::endl; 
于 2012-08-22T03:21:34.097 回答
1

grandchildisT和 size 的类型是N; 那么下面是为数组创建引用的方法。

void myFunc(P& first, P& last) {
  T (&g)[N] = first.child.grandchild;
  ...
}

我不喜欢这里的指针,尽管它也是一种可能的方式。因为,数组的静态大小有助于静态分析器进行范围检查。

如果您使用的是 C++11 编译器,那么auto这是最好的方法(@SethCarnegie 已经提到过):

auto &g = first.child.grandchild;
于 2012-08-22T03:31:30.830 回答