C++:创建一个对象数组
C++ : Creating an array of objects
我有以下类:
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];
来提高安全性。
相关文章:
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何使用指针传递给函数的数组中对象的函数成员
- 为什么数组中对象的析构函数在被另一个对象替换时不被调用?
- C++ 从名称数组创建对象
- 具有公共内存区域的类似数组的对象
- 如何声明包含整数数组的对象
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- C++包含使用 unique_ptr 的字符数组的对象
- 如何初始化数组指针对象
- C 数组指向对象错误
- 使用 std::array vs 数组传递对象数组
- 具有对象数组的对象
- 使用数组对对象的编译时多态性是否可行?
- 堆数组中对象的构造函数
- 无法修改数组中对象的队列
- 使用数组作为对象调用派生类的方法
- 如何使函数返回指针到C 中的数组或对象
- 从另一个类访问指针数组的对象
- 如何声明二维数组的对象和返回它从一个函数
- 一个类的数组中对象的最大数目