我有两个类 - 母亲(基地)和女儿(派生)。我继承了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;
}
运行你的代码的结果是什么? – tmpearce
我是桑迪 我的名字是莎拉 程序以退出代码结束:0 – familyGuy
因此,他们每个人都有一个名为'sayName()'的函数,并且每个函数都被调用......这与重写无关,继承或类似的东西。 – tmpearce