匿名聚合中不允许构造函数,结构中的字符串

编程入门 行业动态 更新时间:2024-10-27 18:19:38
本文介绍了匿名聚合中不允许构造函数,结构中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我尝试创建和使用的这个结构体出现错误.使用字符而不是字符串的结构有效,但我发现我将需要能够存储许多字母.使用下面这个小代码示例后,我收到此错误:

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; };

更多推荐

匿名聚合中不允许构造函数,结构中的字符串

本文发布于:2023-10-23 04:25:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519780.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中不   函数   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!