如何使所有数组元素可访问

时间:2014-04-07 15:41:38

标签: c++ arrays class pointers

我一直试图让数组元素可以访问,但到目前为止我还没有成功。这是代码,我已经根据给定的分配创建了它。

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

class Matrix_1D
{
private:
    int *p2values;
    int num_elements;
public:
    Matrix_1D(int *p2v, int n); // CTOR
    ~Matrix_1D(); // DTOR
    void show();
};

Matrix_1D::Matrix_1D(int *p2v, int n)
{
    n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
    num_elements = n;
    p2values = new int [n];
    for(int i = 0; i<num_elements; i++)
        p2values[i] = p2v[i];
}

Matrix_1D::~Matrix_1D()
{
    delete [] p2values;
}

void Matrix_1D::show()
{
    for(int i=0; i<num_elements; i++)
        cout << p2values[i] << endl;
}

int main()
{
    int array_a[] = {5,3,5};

    Matrix_1D fkt_1D_a(array_a, sizeof(array_a)/sizeof(int));

    fkt_1D_a.show();

    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

获取int数组大小的正确C ++方法是使用模板:

template <typename T, size_t N>
size_t size(T (&)[N]) {
    return N;  // size of array
}

答案 1 :(得分:1)

Matrix_1D::Matrix_1D(int *p2v, int n)
{
    n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
    num_elements = n;
    p2values = new int [n];
    for(int i = 0; i<num_elements; i++)
        p2values[i] = p2v[i];
}

正如您所述,sizeof p2v是指针的大小,因此您不知道数组有多大。相反,使用传入的参数但不覆盖它:

Matrix_1D::Matrix_1D(int *p2v, int n)
{
    // you don't need the first line at all.
    num_elements = n;
    p2values = new int [n];
    for(int i = 0; i<num_elements; i++)
        p2values[i] = p2v[i];
}