 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Sun May 20, 2007 9:11 am Post subject: C++ Syntax Confusion |
|
|
Given the template class below, please help me understand the
following code behavior?
Array<int32> ia(10); // Array that can contain 10 int32
ia[1] = 1; // Array element 1 set to 1
Here comes the confusion part.
Array<int32> *iarrayPtr = new Array<int32>(10);
1. Does the above mean a point to an array that can contain 10
int32 ?
(*iarrayPtr)[1] = 99;
2. Assign value 99 to array element 1.
iarrayPtr[2] = 100;
3. Stepping through with the debugger, I can see Array(int32 aSize)
called with aSize set to 100. What happened here? How should I read
the above code statement?
Thanks!!!
=== ===
template<class T>
class Array :{
public:
Array(int32 aSize){dataLen = aSize;data = new T[dataLen];}
virtual ~Array(){delete [] data;}
int32 length() const{return(dataLen);}
const T& operator[](int32 i) const {return(data[i]);}
T& operator[](int32 i){return(data[i]);}
T *getData() const {return(data);}
private:
Array();
private:
T *data;
int32 dataLen;
}; |
|
| Back to top |
|
 |
Guest
|
Posted: Sun May 20, 2007 9:11 am Post subject: Re: C++ Syntax Confusion |
|
|
| Quote: | Array<int32> *iarrayPtr = new Array<int32>(10);
1. Does the above mean a point to an array that can contain 10
int32 ?
|
Ya
| Quote: | 2. Assign value 99 to array element 1.
iarrayPtr[2] = 100;
|
Here you're viewing your pointer as an array of Array<int32>
(pointers can be viewed as arrays, and an array can be viewed as r-
value pointer to its first element in C/C++). Thus you access its
third element (third Array<int32>, which you obviously didnt allocate
memory for). Now, when you toss 100 in there, an implicit convertion
takes place:
consturctor Array(int32 aSize) - gives compiler rights to implicitly
convert int32 to Array using this constructor. If you want to avoid
such errors, put explicit in front of constructor declaration:
explicit Array(int32 aSize);
Then you would need to type:
iarrayPtr[2] = Array<int32>(100);
for this to compile successfully. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|