简体   繁体   English

指向C ++中数组对象的指针

[英]Pointer to array object in c++

I'm sort of new to C++ (coming from Java) and I want to declare an array object in a class, but it requires an integer value in its template parameters. 我是C ++的新手(来自Java),我想在一个类中声明一个数组对象,但是它的模板参数需要一个整数值。 I figured I'd have to make a pointer to an array class, but it does not work.. 我想我必须要创建一个指向数组类的指针,但是它不起作用。

I want to make something like: 我想做类似的事情:

class foo{
    private:
        array *myArray;
    public:
        foo(int size){
            //This line may be terribly wrong, but you see what I mean
            myArray = new array<int,5>(); 
        }
        ~foo(){
            free(myArray);
        }
}

Though, the correct initialization of an array object is: 但是,数组对象的正确初始化是:

array<int,5>

but this way does not let me choose length in runtime. 但是这种方式不允许我在运行时中选择长度。

I highly recommend that you pick up a good introductory C++ book , and forget about Java. 我强烈建议您拿起一本很好的C ++入门书 ,而忘了Java。 Seriously, thinking in Java is counterproductive when learning C++. 认真地讲,在学习C ++时,用Java思考会适得其反。 They may have similar syntax but they have very, very different semantics. 它们可能具有相似的语法,但是它们具有非常不同的语义。

The issues you're having is related to fundamental concepts of the language. 您遇到的问题与语言的基本概念有关。 You have to learn the fundamentals from a good C++ introductory book before moving on. 在继续之前,您必须从一本好的C ++入门书中学习基础知识。


std::array (if that's what you're using) is not the correct class to use for this particular application, because of the fact that you want to choose the length at runtime. 由于要在运行时选择长度,因此std::array (如果您正在使用的)不是用于此特定应用程序的正确类。 The size of the std::array is fixed at compile-time. std::array的大小在编译时固定。

You should use std::vector instead, which allows you to specify (and change) the size at runtime. 您应该改用std::vector ,它允许您在运行时指定(和更改)大小。

The standard containers such as std::vector manages the memory for you; 标准容器(例如std::vector为您管理内存; you don't need to new or delete the standard containers. 您不需要newdelete标准容器。 The standard containers exist because so you don't have to manually deal with memory yourself. 存在标准容器是因为您不必自己手动处理内存。

#include <vector>

class foo
{ 
private: 
    std::vector<int> myArray; 
public: 
    foo(int size) : myArray(size) // Sets the size of the array
    {
    } 

    ~foo()
    { 
        // You don't need to delete anything; the vector takes care of itself.
    } 
};

Notice that I didn't use pointers, new , delete , malloc() , or free() anywhere here. 注意,我在这里的任何地方都没有使用指针newdeletemalloc()free() You often don't need pointers for many, many cases in C++ . 在C ++中,很多情况下通常不需要指针 Contrary to popular belief, there's very little manual memory management that you actually have to do when using modern C++ techniques. 与流行的看法相反,使用现代C ++技术时,您实际上几乎不需要执行手动内存管理。 In fact, if you're using delete or free() in your C++ code, you're probably doing it very wrong. 实际上,如果在C ++代码中使用deletefree() ,则可能做错了。

I would like to stress again the importance of a good introductory C++ book in assisting you with the language. 我想再次强调一本良好的C ++入门书对帮助您使用该语言的重要性。 Any good intro C++ book will cover std::vector and how to use it to your advantage. 任何优秀的C ++入门书籍都将介绍std::vector以及如何利用它来发挥您的优势。 Other resources such as a std::vector reference can also be of assistance. 其他资源, 例如std::vector引用也可以提供帮助。 Familiarize yourself with them. 熟悉它们。

I believe what you're looking for is a vector class. 我相信您正在寻找的是vector类。 It's a contiguous array-like storage structure (nice stackoverflow question ), and a C++ alternative to C arrays. 它是一个类似数组的连续存储结构(不错的stackoverflow问题 ),是C数组的C ++替代方案。

You can do it with a pointer, but since vector is dynamically growing in size, it's not that important. 您可以使用指针来完成此操作,但是由于vector大小是动态增长的,因此它并不那么重要。

Here's an example from your example: 这是您的示例中的一个示例:

#include <vector>

class foo{
    private:
        std::vector<int> *vecPointer;
    public:
        foo(int size){
            vecPointer = new std::vector<int>(size, 0);
                // 0 as default value, can be omitted
        }
        ~foo(){
            delete vecPointer;
        }
}

An alternative, if you just want to reserve memory, but don't actually have elements at the time of class initialization, would be to just reserve the memory instead of filling it with concrete int values. 如果您只想保留内存,但在类初始化时实际上没有任何元素,则可以选择保留该内存,而不用具体的int值填充它。 In that case, the constructor would look something like: 在这种情况下,构造函数将类似于:

foo::foo(int size){
     vecPointer = new std::vector<int>();
     vecPointer->reserve(size);
}

The destructor does not change, and inside the class foo , you can add object up to the reserved size with vecPointer->push_back(5) , and you can add more objects than that in exactly the same way (only after that the vector size and the memory it takes will grow). 析构函数不会改变,并且在class foo ,您可以使用vecPointer->push_back(5)将对象添加到保留的大小,并且可以以完全相同的方式添加更多的对象(仅在矢量大小之后)并且所需的内存将会增加)。

Also, do you really want to use pointers? 另外,您真的要使用指针吗? You don't have to, you could just have a normal vector: 您不必这样做,可以有一个法线向量:

#include <vector>

class foo{
    private:
        std::vector<int> vec;
    public:
        foo(int size){
            vec.resize(size, 0); // it's initialized as empty here
            // alternative, with reserve:
            // vec.reserve(size);
        }
        ~foo(){
            // no deletion needed like this
        }
}

This way, everything is taken care of and you don't have to remember to delete. 这样,一切都得到了照顾,您不必记住删除。

foo(int size) {
    myArray = new int[size];  // Allocate n ints and save ptr in a.
    for (int i=0; i<size; i++) {
        myArray[i] = 0;    // Initialize all elements to zero. 
}

Other answers have answered the question nicely (you don't need to manage memory), but suppose you want to manage memory yourself (using new operator)- 其他答案很好地回答了这个问题(您不需要管理内存),但是假设您想自己管理内存(使用新的运算符),

then use a Unique pointer ( smart pointers ) to point to the array. 然后使用唯一指针( 智能指针 )指向数组。

#include <memory>

class foo{
    private:
        std::unique_ptr<int> myArray;
    public:
        foo(int size){
            myArray.reset(new int[5]); 
        }
        ~foo(){
        }
}

You don't need to release memory here (just like vectors). 您无需在这里释放内存(就像向量一样)。

But remember the best solution is to use vectors (as pointed out), but since the question title read "Pointer to array", I have added a way to smartly point to array. 但是请记住最好的解决方案是使用向量(如所指出的那样),但是由于问题标题为“ Pointer to array”,因此我添加了一种巧妙地指向数组的方法。

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

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