I'm relatively new to c++ and so i don't know how to implement my problem. I will schematically present my problem instead of the actual code, hopefully this will give general solutions that other users can use as well.
I have:
a class A defined in a header Ah (with its proper A.cpp)
a class B in header Bh (with its proper B.cpp)
in this class B, I have a function that uses as argument an object of A (objA), does something with it, and returns this object.
How should I define that function so that the class B recognizes the "type" objA in its function? Is it done with pointers, templates,...?
Thanks! Roeland
Your headerB.h should #include "headerA.h"
. That would suffice.
Of course if you are going to change state of the object, you should pass it by pointer, something like void MyBMethod(objA* x);
.
There're there variants:
// 1) by value
// in B.h
#include "A.h"
class B {
public:
A foo(A a);
};
// in B.cpp
A B::foo(A a) { /* a.do_something(); */ return a; }
// 2) by reference
// in B.h
#include "A.h"
class B {
public:
void foo(A& a); // can modify a
void foo(const A& a); // cannot modify a
};
// in B.cpp
void B::foo(A& a) { // a.change_something(); }
void B::foo(const A& a) { // a.get_something(); }
// 3) by pointer
// in B.h
#include "A.h"
class B {
public:
void foo(A* a); // can modify a
void foo(const A* a); // cannot modify a
};
// in B.cpp
void B::foo(A* a) { // a->change_something(); }
void B::foo(const A* a) { // a->get_something(); }
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.