【发布时间】:2019-06-10 01:38:31
【问题描述】:
我写了以下代码:
// 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 函数,这样它会说 它会说“你好我的名字是特里”而不是“你好我的名字是克莱尔”。
【问题讨论】:
-
顺便说一句,在
Daughter类中声明int age;可能没有意义,因为该变量已经存在于Mother类中。如果你也在Daughter类中声明它,那么每个Daughter都会有两个年龄,这可能不是你想要的。更好的方法是像这样编写Daughter构造函数,以便将a参数传递给Mother的构造函数:Daughter(int a) : Mother(a*2) {} -
这种继承设置意味着每个
Daughter也是一个Mother。这没有意义,但大概是因为这只是一个例子。
标签: c++ inheritance subclass superclass