简体   繁体   中英

error: non-aggregate type 'Circle' cannot be initialized with an initializer list

I'm in need of help with an assignment for my C++ class. My problem is trying to compile a program I got from my professor. Every time I try to compile the code I get the following error

"error: non-aggregate type 'Circle' cannot be initialized with an initializer list

 Circle list[] ={ { 93, "yellow" }, 

same error follows for the second circle in the array. Can someone tell me what I need to do to get this code to compile?

#include <iostream>
#include "Circle.h"
#include <string>
using namespace std;

int main()
{
 Circle list[] ={  { 93, "yellow" },
                   { 27, "red"    }
                };

 Circle *p;
 p = list;

 cout<<(*p).getRadius()<<endl;
 cout<<(*p).getColor()<<endl;
 cout<<p->getRadius()<<endl;
 cout<<p->getColor()<<endl;

 p++;

 cout<<(*p).getRadius()<<endl;
 cout<<(*p).getColor()<<endl;
 cout<<p->getRadius()<<endl;
 cout<<p->getColor()<<endl;

 return 0;
}//end main

What version of C++ are you using? Before C++11, any class with at least one constructor could not be constructed using an aggregate list:

struct A
{
    std::string s;
    int n;
};
struct B
{
    std::string s;
    int n;

   // default constructor
    B() : s(), n() {}
};

int main()
{
    A a = { "Hi", 3 }; // A is an aggregate class: no constructors were provided for A
    B b; // Fine, this will use the default constructor provided.
    A aa; // fine, this will default construct since the compiler will make a default constructor for any class you don't provide one for.
    B bb = { "Hello", 4 }; // this won't work. B is no longer an aggregate class because a constructor was provided.
    return 0;
}

I daresay Circle has a constructor defined, and cannot be constructor with an aggregate initialisation list pre C++11. You could try:

Circle list[] = { Circle(93, "Yellow"), Circle(16, "Red") };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM