引入继承x类的对象的函数

时间:2015-12-03 23:33:06

标签: c++ inheritance

如果我要做一个基类:

     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);
     }

1 个答案:

答案 0 :(得分:0)

是的,您可以,doSomehing()SonDaughter继承。但是Father::doSomething()将被执行。如果您将Father::doSomething()标记为virtual,然后在DaughterSon中覆盖它,那么您将实现运行时多态性,即"右"根据实例的类型调用函数。例如:

#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);
}

Live on Coliru

注意:您的代码中有很多拼写错误。更严重的错误是您的doSomething()未标记为const,因此您无法通过const引用来调用它。