类层次结构 – 类没有成员

huangapple go评论80阅读模式
英文:

Сlass hierarchy - class has no member

问题

我有以下类层次结构:

class BaseClass
{
public:
    void SetParent(BaseClass* ptr) { parent = ptr; }
    BaseClass* GetParent() { return parent; };
protected:
    BaseClass* parent;
};

class ClassFirst : public BaseClass
{
public:
    void UniqueMethod() { }
};

class ClassSecond : public BaseClass
{
};

我试图做以下操作:

ClassFirst* first = new ClassFirst;
ClassSecond* second = new ClassSecond;
second->SetParent(first);
second->GetParent()->UniqueMethod();

但是我得到了一个错误:
Class "BaseClass" has no member "UniqueMethod".
那么我该如何访问父类的方法呢?

英文:

I have the next class hierarchy:

class BaseClass
{
public:
    void SetParent(BaseClass* ptr) { parent = ptr; }
    BaseClass* GetParent() { return parent; };
protected:
    BaseClass* parent;
};

class ClassFirst : public BaseClass
{
public:
    void UniqueMethod() { }
};

class ClassSecond : public BaseClass
{
};

I'm trying to do next:

ClassFirst* first = new ClassFirst;
ClassSecond* second = new ClassSecond;
second->SetParent(first);
second->GetParent()->UniqueMethod();

But I get an error:
Class "BaseClass" has no member "UniqueMethod".
So how do I access the parent?

答案1

得分: 0

直接的方法是使用类型转换。目前,在BaseClass中的parent成员没有UniqueMethod()方法。然而,ClassFirst有这个方法。由于我们知道second->GetParent()实际上是ClassFirst类型的对象,我们可以将其转换为该类型的对象,并执行以下操作:

ClassFirst* temp = static_cast<ClassFirst*>(second->GetParent());
temp->UniqueMethod();

如果你不确定parent对象是否实际上是具有UniqueMethod()方法的类的对象(它可能是ClassSecond类型,没有该方法),你可以这样做:

ClassFirst* temp = dynamic_cast<ClassFirst*>(second->GetParent());
if (temp) temp->UniqueMethod();

动态转换如果类型不正确,将返回nullptr。静态转换会抛出错误。

英文:

The straightforward method would be to use a cast. Currently, your parent member within BaseClass does not have a UniqueMethod() method. However, ClassFirst does. Since we know that second-&gt;GetParent() is actually an object of type ClassFirst, we can perform a cast to that type of object, and do this:

ClassFirst* temp = static_cast&lt;ClassFirst*&gt;(second-&gt;GetParent());
temp-&gt;UniqueMethod();

If you don't know if the parent object will actually be an object of the class with the UniqueMethod() method (it could be of type ClassSecond, which does not have it), you can do it this way:

ClassFirst* temp = dynamic_cast&lt;ClassFirst*&gt;(second-&gt;GetParent());
if(temp) temp-&gt;UniqueMethod();

Dynamic cast will return nullptr if it is not the correct type. Static cast will throw an error.

huangapple
  • 本文由 发表于 2023年8月8日 22:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定