因此,我尝试创建和使用的这个结构体出现错误.使用字符而不是字符串的结构有效,但我发现我将需要能够存储许多字母.使用下面这个小代码示例后,我收到此错误:
So I have been getting an error with this struct I am trying to create and use. The struct using char's instead of strings worked, but I found that I am going to need to be able to store many letters. Upon using this small sample of code below I get this error:
错误:成员‘std::__cxx11::string GraphNode::::c1’在匿名聚合字符串c1中不允许使用构造函数;
#include <iostream> #include <cstdlib> #include <fstream> #include <functional> #include <queue> #include <vector> #include <string> #include <map> using namespace std; class Node { public: struct { string info; Node *next; int weight; bool activated; }; };我更多的问题是,字符串不能在结构中使用吗?是否有不同的方式来声明这个或其他解决方法?
My more dubbed down question would be, can strings not be used in structs? Is there a different way to declare this or another work around?
推荐答案此代码使用了 C++ 语言的非标准扩展,GCC 文档位于 未命名结构和联合字段.GCC 对该功能的实现不允许未命名结构具有具有非平凡构造函数的成员.Clang 和 MSVC 显然支持类似的扩展,但具有更宽松的限制,因此允许使用 std::string 成员.
This code is using a non-standard extension to the C++ language, which GCC documents at Unnamed Structure and Union Fields. GCC's implementation of the feature does not allow the unnamed struct to have members that have non-trivial constructors. Clang and MSVC apparently support a similar extension but with more liberal restrictions, so that a std::string member is allowed.
最好的解决方案是停止依赖非标准扩展,而只使用适用于任何地方的标准 C++.没有理由在您的示例中使用未命名的 struct,因此只需编写:
The best solution is to stop relying on non-standard extensions and just use standard C++ that works everywhere. There is no reason to use an unnamed struct in your example, so just write:
class Node { public: string info; Node *next; int weight; bool activated; };更多推荐
匿名聚合中不允许构造函数,结构中的字符串
发布评论