【问题标题】:I got a c++ example code with "#include <optional>" and has an error which I can't understand我得到了一个带有“#include <optional>”的c++示例代码并且有一个我无法理解的错误
【发布时间】:2020-07-25 20:23:27
【问题描述】:

我首先尝试理解 c++ 中的 optional(在 g++ 版本 17 中支持) 但是我有一些错误,看起来很简单,但我无法理解....

这是一个简单的例子。

#include <iostream>
#include <optional>
#include <string>
#include <vector>
using namespace std;

struct Animal {
    std::string name;

};

struct Person {
    std::string name;
    std::vector<Animal> pets;

    std::optional<Animal> pet_with_name(const std::string &name) {
        for (const Animal &pet : pets) {
            if (pet.name == name) {
                return pet;
            }
        }
        return std::nullopt;
    }
};

int main() {
    Person john;
    john.name = "John";

    Animal fluffy;
    fluffy.name = "Fluffy";
    john.pets.push_back(fluffy);

    Animal furball;
    furball.name = "Furball";
    john.pets.push_back(furball);

    std::optional<Animal> whiskers = john.pet_with_name("Whiskers");
    if (whiskers) {
        std::cout << "John has a pet named Whiskers." << std::endl;
    }
    else {
        std::cout << "Whiskers must not belong to John." << std::endl;
    }
}

这么简单的代码,我可以理解。但我遇到了一些错误

test.cpp:15:10: error: ‘optional’ in namespace ‘std’ does not name a template type
     std::optional<Animal> pet_with_name(const std::string &name) {
          ^~~~~~~~

我正在运行 Windows 10 中的 Ubuntu 18.04 lts 它不会在

处返回错误
#include <optional>

其g++版本为g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

【问题讨论】:

  • 你如何编译你的代码?你启用 C++17 了吗?
  • 你为g++开启c++17模式了吗?
  • g++ -o -std=c++17 test.cpp 将生成一个名为-std=c++17 的输出文件。您需要更加小心您的选项规范。
  • 投票结束,因为错字。 -o 标志需要一个参数,即可执行文件的名称。如果你的代码编译成功,你最终会得到一个名为-std=c++17 的文件(或者一个错误,说你不能这样命名文件)。删除 -o 标志或提供正确的文件名
  • 内联代码可以通过将其放在``(反引号)中来创建。见help pages for comment formatting

标签: c++ optional


【解决方案1】:

您需要一个最新的编译器并使用 C++17 标志编译上述代码,如下所示。

g++ -std=c++1z main.c 

这里的 main.c 是包含您的代码的文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多