C++ cpp从需要超类对象的函数访问子类对象方法
我编写了以下代码:C++ cpp从需要超类对象的函数访问子类对象方法,c++,inheritance,subclass,superclass,C++,Inheritance,Subclass,Superclass,我编写了以下代码: // constructors and derived classes #include <iostream> using namespace std; class Mother { public: int age; Mother() { cout << "Mother: no parameters: \n" << this->age << endl;
// 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);
}
//构造函数和派生类
#包括
使用名称空间std;
班主任
{
公众:
智力年龄;
母亲()
{
CUT你所要的是“多态行为”(或“动态调度”),它是C++的基本特征。要启用它,你需要做两件事:
用virtual
关键字标记sayhello()
方法(即virtual void sayhello()
而不仅仅是void sayhello()
)
将greet()
方法的参数更改为按引用传递或按指针传递,以避免对象切片问题(即int greet(const Mother&m)
而不是int greet(Mother m)
)
完成后,编译器将智能地选择哪个sayhello()
方法在运行时根据m
参数的实际对象类型调用,而不是在编译时根据greet
函数的参数列表中显式列出的类型对选择进行硬编码。您要求的是所谓的“多态行为”(或“动态分派”)它是C++的一个基本特性,为了实现它,您需要做两件事:
用virtual
关键字标记sayhello()
方法(即virtual void sayhello()
而不仅仅是void sayhello()
)
将greet()
方法的参数更改为按引用传递或按指针传递,以避免对象切片问题(即int greet(const Mother&m)
而不是int greet(Mother m)
)
完成后,编译器将智能地选择哪个sayhello()
方法在运行时根据m
参数的实际对象类型调用,而不是在编译时根据greet
函数的参数列表中明确列出的类型对选择进行硬编码。顺便说一句,在子类中声明int age;
可能没有意义,since该变量已经存在于母亲
类中。如果您也在女儿
类中声明它,那么每个女儿
都将有两个年龄,这可能不是您想要的。更好的方法是像这样编写女儿
构造函数,以便A
参数传递给母亲的构造函数:女儿(inta):母亲(a*2){
此继承设置意味着每个子
也是母。这没有意义,但可能只是一个示例。顺便说一句,在子类中声明int age;
可能没有意义,因为该变量已经存在于母类中。如果您也可以在子类中声明它,那么每个子类将有两个年龄,这可能不是您想要的。更好的方法是这样编写子类的构造函数,以便A
参数传递给母类的构造函数:子类(inta):母亲(a*2){}
这个继承设置意味着每个女儿也都是母亲
。这没有意义,但可能只是一个例子。