简体   繁体   中英

how to pass information from one class to another

I am using a function which will take states of both classes how should I generate that function, right now i'm doing it like this

 if((b1.fxmin>s.xmin&&s.ymin==b1.fymax)&&b1.fxmin<s.xmax&&s.ymin==b1.fymax))
  { 
    collides=true;
    b1.isFiring=false;
  }
Else if((b1.fxmin>s1.xmin&&s1.ymin==b1.fymax)&&b1.fxmin<s1.xmax&&s1.ymin==b1.fymax))
 {
   collides1=true;
   b1.isFiring=false;
 }

In this project a bullet will hit a spider and if its collides then spider will vanish, b1 is the object of class bullet and s1 and s are spiders.

I have seven spiders in this game and I have created 7 collides variable and seven if statements this means that when ever i increase a spider i need to add this collide variable and if statement

I tried to do this in bullet class but couldn't succeed. how should i pass spider object to bullet class?

You can pass a Spider to the bullet class as follows:

// Bullet.h
class Spider;

class Bullet {
  ...
  bool isColliding(const Spider &s);
}

// Bullet.cpp
#include "Spider.h" // or whatever header you're using.
...
bool Bullet::isColliding(const Spider &s) {
  // Collision logic
}

You can then call this function from you main by doing:

if(b1.isColliding(s1)) {
  // Do something.
}

There are lot of ways to do that.. First you have to be specific that the variables that are you comparing from two different classes are private or public variables?

If they are public variables, then pass the address objects to the function as an input arguments...like this function(class1* ptr1, class2* ptr2)...and access those variables using -> inside the function..

But if you are using those variables as a private members to the respective classes, there is one good way to do this..that is called friend classes..you make one class friend to the other..and then you can use that function which has to be member of one class access the variables of the other class even if they are private..google friend classes for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM