Re: class with two dimensional array as a member (I need help)
* Pawel_Iks:
Hello!
I'd like to have a two dimensional array as a member of a class, bu if
I did it in the following way:
class A {
const int n;
int a[n][n];
public:
A(int nn): n(nn) {};
~A() {};
};
this produce error
Yes. 'n' is not a constant known at compile time. In standard C++
and with an array that isn't dynamically allocated (using e.g. 'new'),
the array dimensions must be compile time constants.
, when I changed it to:
class A {
const int n;
int** a;
public:
A(int nn): n(nn) {
for (int i=0;i<n;i++)
a[i]=new int[n];
}
~A() {
for (int i=0;i<n;i++)
delete [] a[i];
}
};
it works fine
You mean, it compiles. :-)
, however when I tried to use it in some program like
this:
int main() {
int x,y;
A a(10);
return 0;
}
program compiled without any problems, but when I run it it was thrown
an unknown exception ...
You haven't initialized the 'a' pointer.
I don't understand what is going on.
See above.
But even if you initialize 'a', you'll run into other problems because
you haven't declared a copy constructor and copy assignment
operator. This means that if you say e.g. 'array1 = array2', both
variables will have the same A::a pointer, and on destruction both
will try to deallocate the same thing. To avoid this you can instead
use e.g. a std::vector for storage, instead of using raw arrays and
pointers.
<code>
class A
{
private:
size_t myN;
std::vector<int> myElements;
size_t indexFor( size_t i, size_t j ) const
{
return myN*i + j;
}
public:
A( size_t n ): myN( n ), myElements( n*n ) {}
int at( size_t i, size_t j ) const
{
return myElements.at( indexFor( i + j ) );
}
int& at( size_t i, size_t j )
{
return myElements.at( indexFor( i + j ) );
}
size_t n() const { return myN; }
};
</code>
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?