获取对象被实例化的对象

Getting the object an object is instantiated from

本文关键字:对象 实例化 取对象 获取      更新时间:2023-10-16

我是c++的新手,我缺少一些术语(无法向Google询问特定的问题),所以我将尽可能地清楚。

假设我实例化了一个类a的对象,然后说,从这个类a对象的方法中,我创建了一个类b的对象。

在我的类B中,我想使用类A的对象作为参数(如果可能的话通过引用传递)。

这可能吗?

谢谢。

很难说你所说的use the object of class A as an argument是什么意思。你是说创造它的那个吗?除此之外,听起来你是在描述一个循环依赖关系。也许这就是你要找的?

//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改为指针。这是推荐的,但你特别要求提供参考。引用还要求AB一样在内存中存在,这可能是一个棘手的保证。

是的,在class A的方法中,您可以使用关键字this引用A的当前实例。例如,您可以为class A提供thisclass B的构造函数。

我的c++语法有点生疏,所以这里有一个c#的例子,可以相当字面地翻译成c++:

public class A
{
    public void MyMethod()
    {
        B b = new B(this);
    }
}
public class B
{
    public B(A parent) { // Do something with A, maybe store it in B for later reference
    }
}

您需要将创建对象作为引用传递给构造函数:

B b(*this);

Where you have:

class B {
public:
   B(const A &creator_) : creator(creator_) { }
private:
   const A& creator;
}

,