错误:无法使用初始值设定项列表初始化非聚合类型 'Circle'



我需要帮助来布置我的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

您使用的是哪个版本的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") };

最新更新