错误:无法使用初始化列表初始化非聚合类型“Circle”

时间:2015-04-28 00:49:59

标签: c++

我需要帮助完成我的C ++类的作业。我的问题是尝试编写一个我从教授那里得到的程序。每次我尝试编译代码时都会出现以下错误

  

“错误:无法使用初始化列表

初始化非聚合类型'Circle'
Circle list[] ={  { 93, "yellow" }, 

对于阵列中的第二个圆圈,会出现相同的错误。有人能告诉我我需要做些什么来编译这段代码吗?

#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

1 个答案:

答案 0 :(得分:2)

您使用的是哪个版本的C ++?在C ++ 11之前,任何具有至少一个构造函数的类都无法使用聚合列表构建:

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

我敢说Circle有一个构造函数定义,并且不能是带有C ++ 11之前的聚合初始化列表的构造函数。你可以尝试:

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