1

假设我有一个对象数组,我想根据它们的数组索引(0、1、4...等)在这些对象中设置变量。有没有办法通过成员函数获取对象的索引(在其父数组中),即不传递整数?

编造的例子:

class Car
{
    public:
        void init();
    private:
        short weight;
};

void Car::init()
{
    // affect 'weight' based on object's array index
}

Car myCars[7];

myCars[2].init();

有没有办法从 init() 中检索 myCars 的索引(即2),而函数没有从外部接收整数?

我知道这没有必要,但我很好奇这是否可能。

谢谢你。

4

3 回答 3

4

您愿意为该init方法提供更多信息吗?您可以使用一些指针算术执行以下操作:

#include <iostream>

using namespace std;

class Car
{
    public:
        void init(const Car*);
    private:
        short weight;
};

void Car::init(const Car* arr)
{
    // affect 'weight' based on object's array index
    int idx = this - arr;
    cout<< "My index: " << idx << endl;
}

int main()
{
  Car myCars[7];

  for(int i = 0 ; i < 7 ; ++i)
    myCars[i].init(myCars);
  return 0;
}
于 2013-01-16T16:54:18.743 回答
2

不,C++ 语言不提供这种能力。如果你真的需要它(仔细检查你的设计),如果你的对象的索引发生变化(例如,如果你插入容器的中间),你必须将它传入并维护它。

于 2013-01-16T16:49:36.303 回答
1

不。

但作为替代方案,您可以将初始化移动到构造函数(如果适用)。创建数组时会自动调用它。但这也不会让您根据索引调整权重。

于 2013-01-16T16:49:29.360 回答