【问题标题】:Need help decoding this typedef需要帮助解码此 typedef
【发布时间】:2018-07-16 09:09:06
【问题描述】:

我正在尝试创建对数组的引用。
它是这样工作的:

typedef int array_type[100];

int main() {
    int a[100];
    array_type &e = a;    // This works
}

但后来我试图删除typedef,并让同样的事情正常工作。没有成功。

int main() {
    int a[100];
    // int[100] &e = a;    // (1) -> error: brackets are not allowed here; to declare an array, place the brackets after the name
    // int &e[100] = a;    // (2) -> error: 'e' declared as array of references of type 'int &'
}

我对@9​​87654324@ 的解释有什么问题?我怎样才能删除typedef,仍然获得相同的功能。

【问题讨论】:

  • 我建议保留 typedef - 它极大地提高了可读性
  • 我试图了解 typedef 的工作原理。因此尝试将其删除。

标签: c++ arrays c++11 reference typedef


【解决方案1】:

您需要添加括号来说明这是对数组的引用,而不是数组的引用。例如

int (&e)[100] = a;

或使用autodecltype(均自C++11 起)使其更简单。

auto& e = a;
decltype(a)& e = a;

【讨论】:

  • 谢谢。这行得通。但是我怎么知道要在(&e) 周围放置一个括号?
  • @vishal 记住它。 :) 好吧,如果你写类似int a[100]; 的东西,a 将被视为 100 个ints 的数组。如果你写int& a[100];a 将是一个包含 100 个int&s 的数组(因此它的格式不正确)。所以你必须用括号来告诉它不是数组,而是对数组的引用。它与指向数组的指针相同。例如如果你想要一个指向 100 个 ints 数组的指针,你必须写 int (*a)[100];。顺便说一句:函数指针也有类似的问题。
  • @vishal :请记住,C 类型是 read from the inside out in a clockwise spirale 是对 100 个 ([100]) ints 的引用 (&) 和数组。跨度>
【解决方案2】:

如果你想避免这种混淆,这实际上是转移到模板类型的好机会,因为有std::array。除其他外,它们提供了在某种程度上统一您需要使用的语法的方法,并且如本例所示,消除了引用/数组/...的混淆。

int main() 
{
    std::array<int, 100> a;
    std::array<int, 100>& e = a;
}

没有什么能阻止您仍然提供类型别名:

using array_type = std::array<int, 100>;

【讨论】:

    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多