一个类的对象数组

anu*_*294 1 c++

#include<iostream.h>
class test{
    int a;
    char b;
public:
    test()
    {
        cout<<"\n\nDefault constructor being called";
    }
    test(int i,char j)
    {
        a=i;
        b=j;
        cout<<"\n\nConstructor with arguments called";
    }
};
int main()
{
    test tarray[5];
    test newobj(31,'z');
};
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中我们可以将值初始化为tarray[5]

vav*_*ava 7

test  tarray[5] = {test(1, 2), test(), test(5, 6), test()};
Run Code Online (Sandbox Code Playgroud)

第五个元素将使用默认构造函数初始化.

//here length of array will be inferred from number of initializers,
//   so it's going to be 4
test  tarray[] = {test(1, 'a'), test(), test(5, 'b'), test()};
Run Code Online (Sandbox Code Playgroud)

  • @ anurag18294:tarray是`test`的数组,不是`test`的实例.但是,它的成员是`test`的实例.换句话说,没有`tarray.b`,只有`tarray [0] .b`,`tarray [1] .b`等. (3认同)