如果我要做一个基类:
class Father
{
public:
void doSomething();
};
然后如果我要做这些课程:
class Daughter : public Father
{
};
class Son : public Father
{
};
我可以使用一个能够摄入对象并执行其doSomething()
void function(const &Father thing)
{
thing.doSomething
}
int main()
{
Son son();
Daughter daughter();
function(son);
function(daughter);
}
答案 0 :(得分:0)
是的,您可以,doSomehing()
由Son
和Daughter
继承。但是Father::doSomething()
将被执行。如果您将Father::doSomething()
标记为virtual
,然后在Daughter
和Son
中覆盖它,那么您将实现运行时多态性,即"右"根据实例的类型调用函数。例如:
#include <iostream>
class Father
{
public:
virtual void doSomething() const {std::cout << "Father\n";}
virtual ~Father() = default;
};
class Daughter : public Father
{
void doSomething() const override {std::cout << "Daughter\n";}
};
class Son : public Father
{
void doSomething() const override {std::cout << "Son\n";}
};
void function(const Father& thing)
{
thing.doSomething();
}
int main()
{
Son son;
Daughter daughter;
function(son);
function(daughter);
}
注意:您的代码中有很多拼写错误。更严重的错误是您的doSomething()
未标记为const
,因此您无法通过const
引用来调用它。