簡體   English   中英

我有一個 c++ 示例代碼,帶有“#include<optional> ” 並且有一個我無法理解的錯誤</optional>

[英]I got a c++ example code with “#include <optional>” and has an error which I can't understand

我首先嘗試了解 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++17 標志編譯上述代碼,如下所示。

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

這里 main.c 是包含您的代碼的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM