【发布时间】:2021-07-05 16:38:58
【问题描述】:
我明白这是如何朝着相反的方向发展的。但是由于各种原因我想使用基类对象来调用派生类方法
假设我们有 2 个类,一起代表一个人的数据(姓名和年龄):
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...
}
class Info: public Person
{
protected:
int age; /// may be more than one parameter.
public:
/// constructors, operator=, destructors, methods and stuff...
int get_age() const; /// method i want to call with a class Person object
{
return y;
}
}
由于这两个类是关于一个人的数据,并且我有一个 Person 对象,我也想使用这个对象来找出他的年龄(可能从它的派生类 Info 中调用 get_age() 方法)
看到了一些纯虚方法,但我不知道如何在 main 中正确调用该虚函数。
我该怎么做? (如果您也可以向我展示程序的主要内容,我会很感激)。
【问题讨论】:
-
您的
main有正确的想法,尽管它的示例太不完整,无法解释为什么会得到意外的输出。 -
如果人没有get_age方法,你怎么能调用它?
-
另外你没有正确分配myinfo,应该是
Info* myinfo = new Info; -
我看到很多指针,但在您的代码中没有创建一个对象。你能edit 你的问题包括minimal, reproducible example 吗?
-
继承关系不对。不能合理地说
Info是Person。搭配组合效果更好。
标签: c++ class inheritance downcast pure-virtual