c++ - 我得到了一个带有“#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++17 标志编译上述代码,如下所示。
g++ -std=c++1z main.c
这里 main.c 是包含您的代码的文件。
推荐阅读
- python - numpy 的 argpartition 如何在文档的示例中起作用?
- multithreading - JMeter: How do I inject specific range of values in 2 different parameters of http requests
- python-3.x - Why does Pygame NEED an event handler to function?
- c# - datagridview中的到期日期需要通知
- swift - 从 Firebase 获取多级节点
- c# - 无法从 Json C# 获取特定字符串
- android - 如何在android studio中获取applicationid?
- laravel - 如何使用 Laravel Rinvex 属性?
- python - 如何在python中生成唯一模值的随机数
- c++ - 调试断言失败 C++:向量下标超出范围