2016-09-25 78 views
-2

我有两个类 - 母亲(基地)和女儿(派生)。我继承了Mother类的一个函数,并试图在Daughter类中重写。它看起来像它覆盖,但我的困惑是,即使我没有继承母亲类,该功能仍然有效,所以我如何继承/覆盖它?我很困惑,好像我真的继承/重写任何东西。请注意派生类,我不是继承: 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; 
} 
+0

运行你的代码的结果是什么? – tmpearce

+0

我是桑迪 我的名字是莎拉 程序以退出代码结束:0 – familyGuy

+2

因此,他们每个人都有一个名为'sayName()'的函数,并且每个函数都被调用......这与重写无关,继承或类似的东西。 – tmpearce

回答

1

,但我的困惑是,即使我不继承母类,功能仍然有效,所以我应该如何继承/覆盖它?我很困惑,好像我真的继承/重写任何东西。

  • 你真的不覆盖sayName()你妈妈类的,因为(如你所说)女儿类不摆在首位继承它。也就是说,你需要先继承一个类,以便能够覆盖虚拟函数。

  • 第二次调用sayName()的原因是它调用了一个女儿类的成员函数,它完全独立于Mother类。需要注意的是,仅仅有多个独立的阶级,其成员函数共享相同的签名不是压倒一切

  • 侧面说明:您不应该包括在Daughter.hpp Mother.cpp,你是否打算继承母亲的女儿,或不。