有什么方法可以将指针指向孩子范围内的父母(派生)班级

Is there any way to have a pointer to a parent (derived) class inside the scope of the Child?

本文关键字:父母 范围内 派生 班级 孩子 方法 什么 指针      更新时间:2023-10-16

假设以下内容:

class child : public parent
{
  public:
  fun1(parent * obj);
  //somewhere on the child class:
  fun2 ()
  {
    fun1(this::...POINTER TO THE PARENT....); //how can I do such a thing without having to create an object of parent class?
  }
};

我正在寻找类似于"这个"指针的东西,该指针指向当前类的地址。但是,是否有"这个"的东西可以在孩子的班级中引用父母班级?

父级是基类而不是派生类。同样,this也可以隐式转换为基类类型,因此您可以将其传递。

在您的情况下:

class child : public parent
{
  public:
  fun1(parent * obj);
  //somewhere on the child class:
  fun2 ()
  {
    fun1(this);
  }
};

最后,在您显示的具体情况下,您要做的事情没有任何意义。孩子可以直接访问基类的任何受保护或公共成员,因此您无需将指针传递给父母。

喜欢以下内容:

class parent
{
    /* Rest of the code here */
protected:
    int m_member;
};
class child : public parent
{
public:
    int fun1() { m_member = 1; } 
};