linked struct

D

dr_tella_nu

Hello World,

the following code throws this error:

error c2039: 'z' : is not a member of 'a'

#include <iostream>

using namespace std;

void main(void)
{
struct a
{
float x, y;
a *next;
};

struct b : public a
{
float z;
};

b* frame1 = new b();
b* frame2 = new b();

frame1->next = frame2;
frame1->z = 3.0;
frame2->z = 5.0;

b* test = (b*)frame1->next;
float c = test->z;
cout << c << endl;

float d = (b*)frame1->next->z; // error
cout << d << endl;
}

furthermore i am not understanding the need of casting
(b*)frame1->next.

please help
Thanks ahead!
 
V

Victor Bazarov

Hello World,

the following code throws this error:

error c2039: 'z' : is not a member of 'a'

Of course. 'z' is not a member of 'a', is it? Why are you surprised?
#include <iostream>

using namespace std;

void main(void)
{
struct a
{
float x, y;
a *next;
};

struct b : public a
{
float z;
};

b* frame1 = new b();
b* frame2 = new b();

frame1->next = frame2;
frame1->z = 3.0;
frame2->z = 5.0;

b* test = (b*)frame1->next;
float c = test->z;
cout << c << endl;

float d = (b*)frame1->next->z; // error

Read up on "precedence" of operations in C++. If you need to access the
'z' member of the 'b' behind the 'next', you need to use parentheses:

float d = ((b*)frame1->next)->z;
cout << d << endl;
}

furthermore i am not understanding the need of casting
(b*)frame1->next.

You're trying to assign the result of evaluating 'next', which has the
type 'a*' to a 'b*'. Such assignment won't work without a cast.

Now, the word of caution: UN-learn to use C-style casts. They are not
good for you. In your case here you need to use 'static_cast<b*>'.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,609
Members
45,253
Latest member
BlytheFant

Latest Threads

Top