继承时如何重写派生类中的函数

How to override a function in derived class when Inheriting

本文关键字:派生 函数 重写 何重写 继承      更新时间:2023-10-16

我有两个类-母亲(基础)和女儿(派生)。我从母亲类继承了一个函数,并试图在女儿类中重写。它看起来像它覆盖,但我的困惑是,即使我不继承母亲类,函数仍然工作,所以我如何继承/重写它?我很困惑,好像我真的继承/重写任何东西。请注意在派生类中,我没有继承: public Mother谢谢你的帮助,一如既往!!

这是我的代码

Mother.hpp

#ifndef Mother_hpp
#define Mother_hpp
#include <iostream>
#include <string>

class Mother
{
public:
    Mother();
    void sayName();
    };

Mother.cpp

#include <iostream>
#include <string>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
Mother::Mother(){}
void Mother::sayName(){
    cout<<"I am Sandy" <<endl;
}

Daughter.hpp

#ifndef Daughter_hpp
#define Daughter_hpp
#include <iostream>
#include "Mother.hpp"
class Daughter : public Mother
{
public:
    Daughter();
    void sayName();
};

Daughter.cpp

#include <iostream>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
Daughter::Daughter() : Mother(){}
void Daughter::sayName(){
    cout << "my name is sarah" <<endl;
}

Main.cpp

#include <iostream>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
    Mother mom;
    mom.sayName();
    Daughter d;
    d.sayName();
    return 0;
}

但我的困惑是,即使我不继承母亲类,函数仍然工作,所以我如何继承/重写它?我很困惑,好像我真的继承/重写了任何东西。

  • 你并没有真正重写你的母类的sayName(),因为(如你所说)子类首先没有继承它。也就是说,您需要首先继承一个类,以便能够重写函数。

  • 你对sayName()的第二个调用有效,因为它是对子类的成员函数的调用,它完全独立于母类。请注意,仅仅拥有多个独立的类,其成员函数共享相同的签名,并不是重写

  • 旁注:无论您是否打算在Daughter中继承Mother,都不应该在Mother.cpp中包含Daughter.hpp。