我写了下面的代码:
// constructors and derived classes
#include <iostream>
using namespace std;
class Mother
{
public:
int age;
Mother()
{
cout << "Mother: no parameters: \n"
<< this->age << endl;
}
Mother(int a)
{
this->age = a;
}
void sayhello()
{
cout << "hello my name is clair";
}
};
class Daughter : public Mother
{
public:
int age;
Daughter(int a)
{
this->age = a * 2;
};
void sayhello()
{
cout << "hello my name is terry";
}
};
int greet(Mother m)
{
m.sayhello();
}
int main()
{
Daughter kelly(1);
Son bud(2);
greet(kelly);
}
我的问题是: 由于 kelly 是从 Mother 派生的类的实例,因此我可以将它传递给需要 mother 类型对象的函数,即。迎接。我的问题是,是否可以从 greet 中调用 sayhello 函数,这样它会说 它会说“你好我的名字是特里”而不是“你好我的名字是克莱尔”。
最佳答案
您所要求的称为“多态行为”(或“动态调度”),它是 C++ 的基本功能。要启用它,您需要做几件事:
使用
virtual
关键字标记您的sayhello()
方法(即virtual void sayhello()
而不仅仅是void sayhello()
)将
greet()
方法的参数更改为按引用传递或按指针传递,以避免对象切片问题(即int greet(const Mother & m)
而不是int greet(Mother m)
)
完成后,编译器将根据 m
参数的实际对象类型,智能地选择在运行时调用哪个 sayhello()
方法,而不是根据 greet
函数的参数列表中明确列出的类型在编译时对选择进行硬编码。
关于c++ - cpp从需要父类(super class)对象的函数访问子类对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54209079/