So I've been trying to learn C++ for the past couple weeks. I tend to think in java logic when coding in C++.
So say in java I have this code:
public class Entity {
public Entity(){
Foobar foobar = new Foobar(this);
}
public void randomMethod(){
System.out.println("I am an entity");
}
}
public class Foobar{
public Foobar(Entity e){
e.randomMethod();
}
}
When I create an instance of Foobar, I want to pass the Entity class it was instantiated in, to the Foobar constructor. I'm having a hard time achieving the same code in C++.
EDIT Basically, I want objects, that are instantiated in another class, to know about it's container class.
This is a C++ version of the Java code in the question. Hope this helps.
class Entity {
public:
Entity();
void randomMethod();
};
class Foobar : public Entity {
public:
Foobar(Entity *e);
};
Foobar::Foobar(Entity *e) {
e->randomMethod();
}
Entity::Entity() {
Foobar *foobar = new Foobar(this);
}
void Entity::randomMethod() {
std::cout << "I am an entity";
}
Unlike Java (which does it invisible), in C++ you have to indicate pointers
yourself.
If you want to reference an existing object you will have to add &
when calling the method and you'll have to specify the parameter with *
to indicate it is a pointer.
public: Foobar(Entity* e)
{ // logic here
}
public: Entity() {
Foobar foobar = new Foobar(this);
}
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.