英文:
С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->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<ClassFirst*>(second->GetParent());
temp->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<ClassFirst*>(second->GetParent());
if(temp) temp->UniqueMethod();
Dynamic cast will return nullptr if it is not the correct type. Static cast will throw an error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论