0

Guys this code gives me error that is "expected unqualified-id before this". I'm doing binary search tree graphics implementation.`

struct node
{
               int data , x  , y;

               node *left;
               this->left->x = this->x+this->x/2;
               this->left->y = this->y + 40;

               node *right;
               this->right->x = this->x/2;
               this->right->y = this->y + 40;
};

But i can't define child node's x and y coordinate. How can i define? `

  • Oh I found solution . I can not define variables in struct . I have to define them by member function. Is that right? – Bayarjargal Jargalsaikhan May 05 '16 at 08:32
  • No that's not right. You can define variables in a struct. That is the purpose of struct. However any operations that you perform on the member variables need to be inside a method. In your case inside the constructor of node. – bashrc May 05 '16 at 08:34
  • @bashrc But the methods don't need to be explicit. For example, `struct foo { int n = 42; };` results in `foo::n` being initialized to `42` whenever a `foo` is default or value initialized. – juanchopanza May 05 '16 at 08:45
  • @juanchopanza That's not a method. Thats just a way of saying that node::n will have a default value of 42. They are called default value initializers. – bashrc May 05 '16 at 08:50

2 Answers2

1

You must create a constructor where the caller can give the values of x and y. That constructor must inicialize the struct Node with the value of x and y:

struct node { int data , x , y;
node *left; node *right;

   node(){};

   node (int x, int y)
       {
       this->x=x;
       this->y=y;

       this->left=new node();
       this->right=new node();

       this->left->x = x+x/2;
       this->left->y = y + 40;

       this->right->x = x/2;
       this->right->y = y + 40;
       }
};

ORParga
  • 392
  • 2
  • 7
-1

You will have to add a method to the node and do your calculations inside that.

struct node
{
   int data , x  , y;
   node *left;
   node *right;

   void init(){
     left->x = x+x/2;
     left->y = y + 40;
     right->x = x/2;
     right->y = y + 40;
   }
};

Once you have filled the node with correct values you can call init on the instance of the node.

node *pNode = new node();
pNode->x =...; pNode->y=...;pNode->left=...; pNode->right...;
pNode->init();
bashrc
  • 4,725
  • 1
  • 22
  • 49
  • This makes it all to easy to run into undefined behaviour by reading from uninitialized objects. – juanchopanza May 05 '16 at 08:46
  • @juanchopanza Yes. And that is why I have called out that before calling init fill the instance with the correct values. From the information that OP has given I cannot predict the implementation of the constructor. – bashrc May 05 '16 at 08:50