,c++,optional"/>

首页 > 解决方案 > 我得到了一个带有“#include”的c++示例代码"并且有一个我无法理解的错误

问题描述

我首先尝试理解 c++ 中的可选(在 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++optional

解决方案


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

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

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


推荐阅读