我是 C++ 的新手,我遗漏了一些术语(无法向 Google 询问具体问题),所以我会尽量说清楚。
假设我已经实例化了一个类 A 的对象。然后说,从这个类 A 对象的方法中,我创建了一个类 B 的对象。
在我的 B 类中,我想使用 A 类的对象作为参数(如果可能,通过引用传递)。
这可能吗?
谢谢。
最佳答案
很难说使用类 A 的对象作为参数
是什么意思。你是说它是从哪一个创建的?除此之外,听起来您在描述循环依赖。也许这就是您要找的东西?
//B.h
class A; //DO NOT INCLUDE. This is called "forward declaration"
class B {
A& parent; //All `A` in this file must be reference or pointer
public:
B(A& a);
};
.
//A.h
#include "B.h"
class A {
B function(); //since it's not reference or pointer, must have include
};
.
//B.cpp
#include "B.h"
#include "A.h"
void B::function(A& a)
: parent(a)
{}
.
//A.cpp
#include "B.h"
#include "A.h"
B A::function()
{
return B(*this);
}
请记住,如果 B::parent
是引用,则不能将 B
分配给另一个,您将失去所有复制语义。如果你需要这些,你必须让 parent
成为一个指针。哪个是推荐的,但是你特地要求引用。只要 B
存在,引用还要求 A
保留在内存中,这可能是一个棘手的保证。
关于c++ - 获取实例化对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7987869/