【问题标题】:How to make all array elements accessible [closed]如何使所有数组元素可访问[关闭]
【发布时间】:2014-04-07 15:41:38
【问题描述】:

我一直在尝试使数组的元素可访问,但到目前为止我还没有成功。这是代码,由于给定的分配,我创建了它。

#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;
}

【问题讨论】:

  • sizeof(AnyPointer) 是一个常量值(取决于目标平台)
  • 那么你的问题是什么?
  • 即使有一个公认的答案,我还是投票结束,因为根本不清楚“使数组的元素可访问”应该是什么意思。你还没有解释你想要完成什么,以及它不工作的方式。由于不清楚所问和回答的内容,因此对未来的读者来说这不是有用的问答。

标签: c++ arrays class pointers


【解决方案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];
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多