创建对象数组c ++ [英] Creating Array of Objects c++

查看:48
本文介绍了创建对象数组c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我理解这一点.

I want to make sure I understand this.

让我们说我有一个Animal类,我想制作一组Animals.

Lets say I have a class Animal and I want to make an array of Animals.

例如,我可以拥有

    Animal animals[10]; 

这给了我一个Animals数组,这样做时会调用默认的复制构造函数,现在我有10个空的Animal对象.

This gives me an array of Animals, when doing this the default copy constructor is called and I now have 10 empty Animal objects.

现在,如果我想开始初始化"它们(我只知道Java),我可以拥有类似的东西

Now if I want to start to "initialize" them (i only know java) I can have something like

    for(int i=0; i<animals.length; i++){
         animals[i] -> hasFur(true);
         Animal -> incCount();
    }

然后这将给我十个动物,每个动物都有毛皮,并且我将一个动物计数器增加到10.

This would then give me ten Animals in an array which all have fur, and I would increment an animal counter to 10.

当你说:

   Animal animals[10];

这些值初始化为什么?

推荐答案

C ++没有为数组提供关联的 length 属性.(请参阅如何找到数组的长度?)

C++ does not have an associated length property for arrays. (See How do I find the length of an array?)

您可以执行以下操作:

int length = sizeof(animals)/sizeof(animals[0]);

然后,在访问元素的成员变量(例如: animals [i]-> hasFur(true); )之前,需要首先创建对象.

Then, before accessing member variables of elements (like this: animals[i] -> hasFur(true);), you need to first create objects.

animals[i] = new Animal(); // assuming the constructor has no arguments

此外, Amimal->incCount()在我看来是个坏主意.您可以在构造函数中增加计数器.这样可以确保您不会意外调用 incCount()并弄乱静态变量的计数.

Also, Amimal -> incCount() looks a bad idea to me. You can increment the counter in your constructor. This way ensures that you don't accidentally call incCount() and mess up the count of your static variable.

这篇关于创建对象数组c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆