获取对象被实例化的对象
Getting the object an object is instantiated from
我是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
改为指针。这是推荐的,但你特别要求提供参考。引用还要求A
和B
一样在内存中存在,这可能是一个棘手的保证。
是的,在class A
的方法中,您可以使用关键字this
引用A
的当前实例。例如,您可以为class A
提供this
给class 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;
}
,
相关文章:
- 对象实例化调用构造函数的次数太多
- 为什么C++无法识别我的对象实例化?
- 使用大括号和 : 符号的对象实例化
- 对象实例化与类型C++
- cpp 静态对象实例化
- 用户创建的类对象实例化的未申请标识符
- 对象实例化后不输出
- 限制对象实例化堆
- 未知的 C++ 对象实例化语法
- 由于命名空间而导致的对象实例化错误
- C 在对象实例化时如何分开声明和构造函数
- JNI Java对象实例化期间的Segfault
- C++ 类文件中的对象实例化
- C++ 中的对象实例化
- 无法理解浮点数和对象实例化之间比较的原因
- C++对象实例化与赋值
- C++:用友元类限制对象实例化
- 将类中的对象实例化数限制为给定数量
- 使用 Sizeof、malloc 和 cast 的 C++ 对象实例化
- 通用成员函数定义,可从 'const' 和 'non-const' 对象实例化