View previous topic :: View next topic |
Author |
Message |
Duncan_L n00b
Joined: 06 Sep 2008 Posts: 42
|
Posted: Sun Sep 21, 2008 2:06 am Post subject: C++ passing class instance as another class's member - help |
|
|
Code: | #include <iostream>
using std::cout;
using std::cin;
using std::endl;
struct myClassA
{
int* my_array; //getting read to make a dynamically allocated array
myClassA()
{my_array=new int[5];} //dynamically allocates array, my_array, with arbitrary size 5
};//end of myClassA structure
struct myClassB
{
myClassA* pt; //I want to be able to use an instance of myClassA as a member in myClassB. I intend to pass it via the constructor.
myClassB(myClassA* myPt) //Constructor takes pointer to instance of myClassA
{pt=myPt;} //I set myClassB's member, pt, to the pointer passed as an argument in the constructor
void myMethod()
{cout<<*pt.my_array[2]<<endl;} //theoretically this should work right??
//error: request for member 'my_array' in '((myClassB*)this)->myClassB::pt', which is of non-class type 'myClassA*'
};
int main()
{return 0;}
|
Can anybody help fix the error I'm getting? (It's a few lines from the end) |
|
Back to top |
|
|
timeBandit Bodhisattva
Joined: 31 Dec 2004 Posts: 2719 Location: here, there or in transit
|
Posted: Sun Sep 21, 2008 3:42 am Post subject: |
|
|
It's a common C pitfall--a simple matter of operator precedence. You need to write either (*pt).my_array[2] or pt->my_array[2].
The dot operator has higher precedence than the dereference operator (*). As written, you've attempted to access a member (my_array) of a pointer, which is of course impossible. Use parentheses to force the pointer dereference to be evaluated first: (*pt). Then you can access members of the pointed-to structure. This is such a common idiom that the language provides an additional operator (->) for the purpose. _________________ Plants are pithy, brooks tend to babble--I'm content to lie between them.
Super-short f.g.o checklist: Search first, strip comments, mark solved, help others. |
|
Back to top |
|
|
Duncan_L n00b
Joined: 06 Sep 2008 Posts: 42
|
Posted: Sun Sep 21, 2008 6:48 am Post subject: |
|
|
oh, cool thanks. |
|
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
|
|