[英]c++: Returning objects in functions of another class
I'm relatively new to c++ and so i don't know how to implement my problem. 我是C ++的新手,所以我不知道如何实现我的问题。 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) 在标头Ah中定义的A类(及其正确的A.cpp)
a class B in header Bh (with its proper B.cpp) 标头Bh中的B类(及其正确的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. 在此类B中,我有一个函数,该函数使用A(objA)的对象作为参数,对其进行处理,然后返回该对象。
How should I define that function so that the class B recognizes the "type" objA in its function? 我应该如何定义该函数,以便类B在其函数中识别“类型” objA? Is it done with pointers, templates,...? 它是通过指针,模板等完成的吗?
Thanks! 谢谢! Roeland Roeland
Your headerB.h should #include "headerA.h"
. 您的headerB.h应该#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);
当然,如果要更改对象的状态,则应通过指针传递它,例如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(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.