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