如何从被传递的对象中通过引用传递 self
How to pass self by reference from within the object being passed?
我对需要使用的语法感到困惑。
我有:
class Foo {
public:
void bar(Baz& grr){
}
}
另一类:
class Baz{
}
和:
class Jay : public Baz{
public:
void doStuff(){
Foo thing();
thing.bar(); //Here is the problem ? How do I pass this instance to this function ?
}
}
如何从doStuff()
内将Jay
实例传递给Foo::bar(Baz& grr)
?如果我尝试使用this
编译器说使用 *
取消引用它。我该怎么做?
尝试完全按照编译器的建议进行操作:
thing.bar(*this);
通过取消引用指针,可以"创建"引用。
this
是指向当前对象的指针。你需要"取消引用"它才能获得对象的引用:
thing.bar(*this);
您可以使用 *
运算符取消引用,如 *this
.取消引用返回指向的对象,由于this
是指向当前实例的指针,*this
将返回当前实例的对象。
但是请注意,如果保存此引用并且该实例超出范围,它将被销毁,并且您将留下一个悬而未决的引用,该引用在尝试读取时会导致未定义的行为。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在默认模板参数中引用 self 类型
- 如何从被传递的对象中通过引用传递 self
- 类实例持有对自身的引用 - self
- 为什么有些类方法返回"*this"(self的对象引用)?
- 为什么通过引用传递self会导致错误的访问
- 无法让 Lua 函数引用"self"
- 如何在声明当前命名空间时引用它?有没有像"self"/"this"这样的词?