简体   繁体   English

创建类时如何定义数组的大小?

[英]How do I define an array's size when the class is created?

I want to create an array contained inside of a class. 我想创建一个包含在类内部的数组。 The array will be of fixed size, but I don't know that fixed size until the constructor of the class. 该数组是固定大小的,但是直到类的构造函数我才知道该固定大小。

Let's say the users create something like: Fibanocci f(value1, value2, size) . 假设用户创建了以下内容: Fibanocci f(value1, value2, size) The size argument would then used to determine the number of elements in the containing array, which will be fixed throughout the entire life of the Fibanocci instance. 然后,使用size参数确定包含数组中元素的数量,该数量将在Fibanocci实例的整个生命周期中固定Fibanocci

How do I pull this off? 我如何做到这一点?

Go with std::vector<type> vector instead and you can do int size = vector.size() . 改为使用std::vector<type> vector ,您可以执行int size = vector.size() You can initialize the size of the vector in the constructor. 您可以在构造函数中初始化向量的大小。 For example, 例如,

// MyClass.hpp
class MyClass
{
public:
    MyClass();

    // Say I know this vector is going to have 5 elements
    std::vector<double> myVector; 
}

// MyClass.cpp
MyClass::MyClass() : myVector(5)
{
    int vectorSize = myVector.size(); //vectorSize = 5
}

This is not possible since C/C++ requires all classes to have constant sizeof . 这是不可能的,因为C / C ++要求所有类都具有恒定的sizeof The only way around is to use heap allocation ( new or std::vector as @jlack proposed or whatever else) 唯一的方法是使用堆分配(@jlack建议的newstd::vector或其他方法)

Array size must be known at compile-time!! 数组大小必须在编译时知道! Don't think you will lose performance by using vector, it's a wrapper over array. 不要以为使用向量会降低性能,它是数组的包装器。 If you are really stringent and have C++11, you can use array from the standard library. 如果您确实很严格并且拥有C ++ 11,则可以使用标准库中的array。

Do I use resize or reserve? 我是否使用调整大小或保留?

Reserve will allocate memory but not insert anything. 保留将分配内存,但不插入任何内容。 Resize will insert copies of default-constructed objects, unless you specify a parameter. 调整大小将插入默认构造的对象的副本,除非您指定参数。

Java makes the array dynamic it will assign size at run time. Java使数组动态化,它将在运行时分配大小。 Proxy class will form whose object is this array. 代理类将形成其对象是此数组的形式。

int a[]=new int[10];

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

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