gpt4 book ai didi

c++ - 有没有办法在子范围内有一个指向父(派生)类的指针?

转载 作者:行者123 更新时间:2023-11-28 01:40:11 26 4
gpt4 key购买 nike

假设如下:

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”指针的东西。但是,在子类中引用父类是否有“this”之类的东西?

最佳答案

父类是基类而不是派生类。此外,this 可隐式转换为基类类型,因此您可以直接传递它。

在你的情况下:

class child : public parent
{
public:
fun1(parent * obj);

//somewhere on the child class:
fun2 ()
{
fun1(this);
}

};

最后,在您展示的具体情况下,您尝试做的事情没有任何意义。子级可以直接访问基类的任何 protected 或公共(public)成员,因此您无需将指针传递给父级。

喜欢以下内容:

class parent
{
/* Rest of the code here */
protected:
int m_member;
};

class child : public parent
{
public:
int fun1() { m_member = 1; }
};

关于c++ - 有没有办法在子范围内有一个指向父(派生)类的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47512195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com