我得到了一个带有"#include"的 c++ 示例代码<optional>,并且有一个我无法理解的错误



我首先尝试理解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是包含您的代码的文件。

最新更新