C++ 如何使用基类对象调用派生类方法?
我明白这是怎么回事。但是由于各种原因,我想使用基类对象来调用派生类方法 假设我们有两个类,一起表示一个人的数据(姓名和年龄): 因为这两个类是关于一个人的数据的,我有一个person对象,我想用这个对象来找出他的年龄(可能从它的派生类Info调用方法get_age()) 看到了一些纯虚拟方法,但我不知道如何正确调用main中的虚拟函数C++ 如何使用基类对象调用派生类方法?,c++,class,inheritance,downcast,pure-virtual,C++,Class,Inheritance,Downcast,Pure Virtual,我明白这是怎么回事。但是由于各种原因,我想使用基类对象来调用派生类方法 假设我们有两个类,一起表示一个人的数据(姓名和年龄): 因为这两个类是关于一个人的数据的,我有一个person对象,我想用这个对象来找出他的年龄(可能从它的派生类Info调用方法get_age()) 看到了一些纯虚拟方法,但我不知道如何正确调用main中的虚拟函数 我怎么做?(如果您也能向我展示程序的main,我将不胜感激)。您可以通过将派生类声明为基类中的虚拟函数来确保该派生类具有要调用的函数。通常使用“纯虚拟函数”(没有
我怎么做?(如果您也能向我展示程序的main,我将不胜感激)。您可以通过将派生类声明为基类中的虚拟函数来确保该派生类具有要调用的函数。通常使用“纯虚拟函数”(没有实现的函数) 像这样:
class Person
{
protected:
char* name; /// may be more than just one. also, heared that std::string is more efficient
public:
/// constructors, operator=, destructors, methods and stuff...
// Pure Virtual Function
virtual int get_age() const = 0; /// force derived classes to implement
};
class Info: public Person
{
protected:
int age; /// may be more than one parameter.
public:
/// constructors, operator=, destructors, methods and stuff...
int get_age() const override /// override here
{
return age;
}
};
您的
main
的想法是正确的,尽管它的示例太不完整,无法解释您为什么会获得意外的输出。如果此人没有get\u age方法,您如何调用它?此外,您没有正确分配myinfo,它应该是Info*myinfo=new Info代码>我看到很多指针,但在代码中没有创建一个对象。你能不能提出一个问题,包括继承关系不正确。不能合理地说信息
就是人
。这是更好的服务与组成。回答不好,得到错误:“无法解析抽象类型的对象Person@RedIcs不幸的是,我不能用一个简单的答案告诉你继承在C++
中是如何工作的。我建议大家多读这方面的内容,尤其是虚拟函数和多态性。@Redlcs答案是正确的。但是,标准中明确规定了语言规则。如果您试图在不了解某些主题的情况下编写代码,那么很自然会遇到这样的错误。尝试此操作将暂时解决您的问题。但这不会给你带来任何好处。您应该很好地学习多态性和虚拟分派机制。人员*p=新信息;
class Person
{
protected:
char* name; /// may be more than just one. also, heared that std::string is more efficient
public:
/// constructors, operator=, destructors, methods and stuff...
// Pure Virtual Function
virtual int get_age() const = 0; /// force derived classes to implement
};
class Info: public Person
{
protected:
int age; /// may be more than one parameter.
public:
/// constructors, operator=, destructors, methods and stuff...
int get_age() const override /// override here
{
return age;
}
};