Re: Why I get error code c2440
Inside the { and } of your constructor, max and max2 are not constants - the
globals const int max and const int max2 have been masked by the
(non-constant) arguments with the same name in the constructor's argument
list.
Array(int max, int max2)
{
capacity = max; // This is max from the argument list
capacity1 = max2; // This is max2 from the argument list
pprime = new long[max][max2]; // Again...
....
}
try this:
class CSomething
{
static const long m_max2 = 3; // This must be initialized with a constant
long m_max;
long (*pprime)[m_max2];
public:
CSomething(long max = 4); // provide a default value (4 here) if you want
~CSomething();
};
// Allocate the array in the constructor
CSomething::CSomething(long max /* = 4 */)
{
m_max = max; // this will be 4 if parameter not specified
pprime = new long[m_max][m_max2];
}
// De-allocate the array in the destructor
CSomething::~CSomething()
{
if(pprime)
delete [] pprime;
}
now, in your program...
int main()
{
CSomething thing1; // Allocates 4 (default) X 3 array
CSomething thing2(2); // Allocates 2 X 3 array
CSomething *thing3;
thing3 = new CSomething(5); // Allocates 5 X 3 array
...
delete thing3; // Destructor deallocates the array
return 0;
// Destructors for thing1 and thing2 are automatically called
}
"Allen Maki" wrote:
/*
When I used the 2 following lines in a simple code, the code will compile
with no error:
long (*pprime)[max2];
pprime = new long[max][max2];
But if I separate the two lines by putting the first in a class
and the second line in the constructor of the same class I will have the
under mentioned error messages.
Can you tell me what is wrong?
*/
#include <iostream>
using namespace std;
const int max = 5;
const int max2 = 4;
class Array
{
public:
long (*pprime)[max2];
int capacity;
int capacity1;
Array(int max, int max2)
{ capacity = max;
capacity1 = max2;
pprime = new long[max][max2];
<------------------------------------------error
//error(1) C2540: non-constant expression as array bound
//error (2)C2440: '=' : cannot convert from 'long (*)[1]' to 'long
(*)[4]'
}
};
int main()
{
return 0;
}
"Allen Maki" <allen_class@hotmail.com> wrote in message
news:u8QRA3hcGHA.1264@TK2MSFTNGP05.phx.gbl...
Hi Everybody,
Iwould apprecite it if you could help.
Allen.
//Why I got the following error message? for the 4th line:
// error C2440: '=' : cannot convert from
//'long (*)[3]' to 'long *' Types pointed
//to are unrelated; conversion requires
// reinterpret_cast, C-style cast or
//function-style cast
#include <iostream>
using namespace std;
int main()
{
const int max = 4; //(1)
const int max2 = 3; //(2)
long *pprime; //(3)
pprime = new long[max][max2]; //(4)
return 0;
}