Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor not allowed in anonymous aggregate, string in struct

Tags:

c++

string

struct

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?

like image 684
Joe Caraccio Avatar asked Dec 08 '16 03:12

Joe Caraccio


2 Answers

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;
};
like image 106
Jonathan Wakely Avatar answered Sep 18 '22 12:09

Jonathan Wakely


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

like image 20
Jesse Laning Avatar answered Sep 18 '22 12:09

Jesse Laning