2015-04-04 105 views
1

我有下面的类的数组:C++:创建对象

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 

但我收到此错误信息:

Error: testing.cpp(40,56):Cannot convert 'char *' to '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个对象。

+0

1.'student :: student'的第三个参数应该是'const char n []',并且2.在'a []中用'}替换每个'('''''''''声明。 – WhozCraig 2015-04-04 04:10:00

+0

@WhozCraig当我这样做时,我得到了大约10条错误消息 – 2015-04-04 04:13:22

+0

[**看到它现场**](http://ideone.com/LWMd5w),并在你的问题中包括你正在使用的* exact *工具链* *。或者,您可以[也只是这样做](http://ideone.com/pGfsww)。 – WhozCraig 2015-04-04 04:15:16

回答

0

在表达式(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];提高安全性。