C++:创建一个对象数组

C++ : Creating an array of objects

本文关键字:数组 一个对象 创建 C++      更新时间:2023-10-16

我有以下类:

class student
{
    int rol , marks;
    char name[20];
    public:
    student(int r , int m , char n[])
    {
         rol = r;
         marks = m;
         strcpy(name,n);
    }
    int roll()
    {
        return rol;
    }
};

现在我正试图创建一个对象数组,比如:

student a[]= {(1,10,"AAA"),(2,20,"BBB"),(3,30,"CCC")}; // I get the error on this line

但我收到了一条错误消息:

错误:testing.cpp(40,56):无法将"char*"转换为"student[]"

当我这样做时:

student a(1,10,"AAAA");
student b(2,20,"BBBB");
student c(3,30,"CCCC");
student d[3]={a,b,c};

它工作得很好。

@WhozCraig Thx很多。这就是我的问题的解决方案:

我必须初始化数组如下:

student a[]= {
    student(1, 10, "AAA"),
    student(2, 20, "BBB"),
    student(3, 30, "CCC")
};

我的初始代码是错误的,可能是因为构造函数一次不能创建多个对象。

在表达式中,(1,10,"AAA")表示应用逗号运算符。要初始化数组,必须提供可以初始化每个数组成员的表达式。因此,一种方法是:

student a[] = {
    student(1, 10, "AAA"),    // creates a temporary student to use as initializer
    student(2, 20, "BBB"),
    student(3, 30, "CCC") };

由于C++11你可以写:

student a[] = {  {1, 10, "AAA"}, {2, 20, "BBB"}, {3, 30, "CCC"} };

因为C++11添加了一个特性,即可以通过大括号括起来的初始值设定项列表来调用对象的构造函数。这和你事后也可以写的原因是一样的:

a[0] = { 4, 40, "DDD" };

注:如评论中所述,char n[]应为char const n[],您可以使用std::string name;而不是char name[20];来提高安全性。