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:
error: member ‘std::__cxx11::string GraphNode::::c1’ with constructor not allowed in anonymous aggregate string 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?
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.
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;
};
Your issue is that string has a user-declared constructor which is not allowed in an aggregate (such as an unnamed struct) as it is a non-POD type. If you gave the struct a name it should fix your issue. For example make it a non-aggregate:
struct data
{
...
};
//or
struct
{
...
} data;
Here is a good explanation of what an aggregate is What are Aggregates and PODs and how/why are they special?
or if you wanted to keep it an aggregate you could do
struct
{
string* info; //change to a pointer
Node *next;
int weight;
bool activated;
};
I am in no way an expert on aggregates or PODs though so someone feel free to correct me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With