2

序言:
我知道有相当多的主题具有相同或相似的标题。继续阅读,您将了解我的情况。


C++ 新手我目前正在阅读一本很明显有一个损坏的示例练习的书。
我的代码

#include <iostream>

using namespace std;

struct Point {
    int x;
    int y;
};

int main(int argc, char const* argv[]) {

    Point p1{100, 200};

    auto [a, b] = p1;

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    auto& [c, d] = p1;

    c += 50;
    d += 50;

    cout << "p1.x = " << p1.x << endl;
    cout << "p1.y = " << p1.y << endl;

    return 0;
}

几乎是这本书的精确副本。我只将原来的一行 cout 拆分为两行,并使用命名空间 std 而不是 std::。除此之外,代码与书中的示例完全相同。

为了 100% 确定我不只是有错字,我从书籍网站下载了示例文件。
我们都得到相同的错误:

structuredBinding.cpp: In function ‘int main(int, const char**)’:
structuredBinding.cpp:14:7: error: expected unqualified-id before ‘[’ token
  auto [a, b] = p1;
       ^
structuredBinding.cpp:16:20: error: ‘a’ was not declared in this scope
  cout << "a = " << a << endl;
                    ^
structuredBinding.cpp:17:20: error: ‘b’ was not declared in this scope
  cout << "b = " << b << endl;
                    ^
structuredBinding.cpp:19:8: error: expected unqualified-id before ‘[’ token
  auto& [c, d] = p1;
        ^
structuredBinding.cpp:19:8: error: expected initializer before ‘[’ token
structuredBinding.cpp:21:2: error: ‘c’ was not declared in this scope
  c += 50;
  ^
structuredBinding.cpp:22:2: error: ‘d’ was not declared in this scope
  d += 50;
  ^

本书假设其示例练习有效,但事实并非如此。
我发现了一些关于这个或类似错误的其他主题,但它们似乎都不适合我。

我还查了勘误表,但没有为本书的那部分记录错误。

我在 Linux (Xubuntu) 上,我用g++ -std=c++17 -o <outputname> <inputname.cpp>

有人可以告诉我这里有什么问题吗?然后我会将该错误报告给作者。

4

1 回答 1

4

要利用 GCC 中的 C++17 功能,您需要传递-std=c++17编译器命令行(例如,通过CXXFLAGS在 Makefile 中进行设置)。

但是,并非所有版本的 GCC 都支持所有 C++17 标准。

根据GCC 中的 C++ 标准支持,您至少需要g++ 7才能利用结构化绑定,而g++ 8才能利用对可访问成员的结构化绑定(例如,来自友元函数的私有成员,而不仅仅是公共成员)。

Ubuntu 16.04 有 g++ 5.4,Ubuntu 18.04 有 g++ 7.3。要在 Ubuntu 上安装较新版本的 g++,请参阅仅在 Ubuntu 18.04 上安装 gcc-8?(也适用于 Ubuntu 16.04)在 Ask Ubuntu 上,尤其是这个 answer

我刚刚在我的 Ubuntu 16.04 系统上安装gcc-8g++-8打包,结构化绑定现在工作正常。

于 2018-12-08T19:12:42.607 回答