【发布时间】: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