假设我具有以下功能:
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
的引用或符号链接(symbolic link)。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;
关于c++ - C++在函数内部创建引用变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12065897/