简体   繁体   English

需要帮助创建一个对象数组

[英]Need help creating an array of objects

I am trying to create an array of class objects taking an integer argument. 我试图创建一个带有整数参数的类对象数组。 I cannot see what is wrong with this simple little code. 我看不出这个简单的小代码有什么问题。 Could someone help? 有人可以帮忙吗?

#include <fstream>
#include <iostream>
using namespace std;

typedef class Object
{
 int var;
public:
 Object(const int& varin) : var(varin) {}
} Object;

int main (int argc, char * const argv[])
{
 for(int i = 0; i < 10; i++)
 {
  Object o(i)[100];
 }

 return 0;
}

In C++ you don't need typedef s for class es and struct s. 在C ++中,对于class es和struct s,不需要typedef So: 所以:

class Object
{
 int var;
public:
 Object(const int& varin) : var(varin) {}
};

Also, descriptive names are always preferrable, Object is much abused. 此外,描述性名称总是可取的, Object被滥用。

int main (int argc, char * const argv[])
{
 int var = 1;

 Object obj_array[10]; // would work if Object has a trivial ctor

 return 0;
}

Otherwise, in your case: 否则,在你的情况下:

int main (int argc, char * const argv[])
{
 int var = 1;

 Object init(var);
 Object obj_array[10] = { var, ..., var }; // initialize manually

 return 0;
}

Though, really you should look for vector 虽然,你真的应该寻找vector

#include <vector>
int main (int argc, char * const argv[])
{
 int var = 1;

 vector<Object> obj_vector(10, var); // initialize 10 objects with var value

 return 0;
}

dirkgently's rundown is fairly accurate representation of arrays of items in C++, but where he is initializing all the items in the array with the same value it looks like you are trying to initialize each with a distinct value. dirkgently的破坏是C ++中项目数组的相当准确的表示,但是他正在用相同的值初始化数组中的所有项目,看起来你试图用不同的值初始化每个项目。

To answer your question, creating an array of objects that take an int constructor parameter. 要回答您的问题,请创建一个带有int构造函数参数的对象数组。 You can't, objects are created when the array is allocated and in the absence of a trivial constructor your compiler will complain. 你不能,在分配数组时创建对象,并且在没有普通构造函数的情况下,编译器会抱怨。 You can however initialize an array of pointers to your object but you really get a lot more flexibility with a vector so my following examples will use std::vector. 但是你可以初始化一个指向你对象的指针数组,但你真的可以通过向量获得更多的灵活性,所以我的下面的例子将使用std :: vector。

You will need to initialize each of the object separately if you want each Object to have a distinct value, you can do this one of two ways; 如果希望每个Object具有不同的值,则需要单独初始化每个对象,您可以使用以下两种方法之一; on the stack, or on the heap. 在堆栈上,或在堆上。 Lets look at on-the-stack first. 让我们先看看堆栈。

Any constructor that take a single argument and is not marked as explicit can be used as an implicit constructor. 任何采用单个参数且未标记为explicit式的构造函数都可以用作隐式构造函数。 This means that any place where an object of that type is expected you can instead use an instance of the single parameter type. 这意味着,在期望该类型的对象的任何地方,您可以改为使用单个参数类型的实例。 In this example we create a vector of your Object class and add 100 Objects to it (push_back adds items to a vector), we pass an integer into push_back which implicitly creates an Object passing in the integer. 在这个例子中,我们创建一个Object类的向量并向其添加100个对象(push_back将项添加到向量),我们将一个整数传递给push_back,它隐式地创建一个传递整数的Object。

#include <vector>
int main() {
    std::vector<Object> v;

    for(int i = 0; i < 100; i++) {
        v.push_back(i);
    }
}

Or to be explicit about it: 或者明确一下:

#include <vector>
int main() {
    std::vector<Object> v;

    for(int i = 0; i < 100; i++) {
        v.push_back(Object(i));
    }
}

In these examples, all of the Object objects are allocated on the stack in the scope of the for loop, so a copy happens when the object is pushed into the vector. 在这些示例中,所有Object对象都在for循环范围内的堆栈上分配,因此当对象被推入向量时会发生复制。 Copying a large number of objects can cause some performance issues especially if your object is expensive to copy. 复制大量对象可能会导致一些性能问题,尤其是如果您的对象复制成本很高。

One way to get around this performance issue is to allocate the objects on the heap and store pointers to the objects in your vector: 解决此性能问题的一种方法是在堆上分配对象并存储指向向量中对象的指针:

#include <vector>
int main() {
    std::vector<Object*> v;

    for(int i = 0; i < 100; i++) {
        v.push_back(new Object(i));
    }

    for(int i = 0; i < 100; i++) {
        delete v[i];
    }
}

Since our objects were created on the heap we need to make sure that we delete them to call their deconstructor and, free their memory, this code does that in the second loop. 由于我们的对象是在堆上创建的,我们需要确保删除它们以调用它们的解构函数并释放它们的内存,这段代码在第二个循环中执行。

Manually calling delete has it's own caveats, if you pass these pointers to other code you can quickly loose track of who owns the pointers and who should delete them. 手动调用delete有自己的注意事项,如果你将这些指针传递给其他代码,你可以快速找到谁拥有指针以及谁应该删除它们。 An easier way to solve this problem is to use a smart pointer to track the lifetime of the pointer, see either boost::shared_ptr or tr1::shared_ptr which are reference-counted pointers : 解决此问题的一种更简单的方法是使用智能指针来跟踪指针的生命周期,请参阅boost::shared_ptrtr1::shared_ptr这些是引用计数指针:

#include <vector>
int main() {
    std::vector<shared_ptr<Object> > v;

    for(int i = 0; i < 100; i++) {
        Object* o = new Object(i);
        v.push_back(shared_ptr<Object>(o));
    }
}

You'll notice that the shared_ptr constructor is explicit, this is done intentionally to make sure that the developer is intentionally stuffing their pointer into the shared pointer. 您会注意到shared_ptr构造函数是显式的,这是有意识地确保开​​发人员有意将其指针填充到共享指针中。 When all references to an object are released the object will automatically be deleted by the shared_ptr, freeing us of the need to worry about it's lifetime. 当释放对对象的所有引用时,shared_ptr将自动删除该对象,从而使我们无需担心它的生命周期。

If you want to stick to arrays, then you must either initialize manually or use the default constructor. 如果要坚持使用数组,则必须手动初始化或使用默认构造函数。 However, you can get some control by creating a constructor with a default argument. 但是,您可以通过使用默认参数创建构造函数来获得某些控制。 This will be treated as a default constructor by the compiler. 这将被编译器视为默认构造函数。 For example, the following code prints out the numbers 0, ..., 9 in order. 例如,以下代码按顺序打印出数字0,...,9。 (However, I'm not sure that the standard dictates that the objects in the array must be constructed in order. It might be implementation dependent, in which case the numbers may appear in arbitrary order.) (但是,我不确定标准是否必须按顺序构造数组中的对象。它可能依赖于实现,在这种情况下,数字可能以任意顺序出现。)

#include <iostream>

using namespace std;

struct A {
   int _val;

   A(int val = initializer()) : _val(val) {}

   static int initializer() { static int v = 0;  return v++; }
};

int main()
{
   A a[10];
   for(int i = 0; i < 10; i++)
      cout << a[i]._val << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM