继承时如何重写派生类中的函数
How to override a function in derived class when Inheriting
我有两个类-母亲(基础)和女儿(派生)。我从母亲类继承了一个函数,并试图在女儿类中重写。它看起来像它覆盖,但我的困惑是,即使我不继承母亲类,函数仍然工作,所以我如何继承/重写它?我很困惑,好像我真的继承/重写任何东西。请注意在派生类中,我没有继承: 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。
相关文章:
- 在派生函数中指定void*参数
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- 从基类数组调用派生函数
- 我设计了一个类并创建了基指针,但是当我尝试通过基指针访问派生函数时,它会出错
- c++ 在派生函数中启动 OMP 线程
- 派生函数的映射
- NIST SP 800-56A 串联/单步密钥派生函数的现有实现
- C++从基类实例调用派生函数
- c++多态性-使用基指针访问派生函数
- 派生函数中的NULL实现
- 与派生函数参数绑定
- 从基类派生函数
- 继承和使用派生函数
- 在列表对象中使用对象的派生函数
- 当派生函数定义了析构函数时,使用复制函数而不是移动函数
- 使用基类的派生函数
- 为什么调用基类函数而不是派生函数
- 多重继承派生类:如何在不重复调用 base 的情况下重用派生函数
- 试图与 Base 中的派生函数交朋友 - 为什么它不起作用?
- 在继续派生函数之前先执行基函数