如何让头文件知道类继承

How to let header file know about class inheritance

本文关键字:继承 文件      更新时间:2023-10-16

>我目前在继承方面遇到了这个问题:

A.hpp

{ 
class Example;
}

A.cpp

{
class Example : public Base {
//OVERRIDE FUNCTIONS OF CLASS HERE
}
}

B.hpp

{ 
class DerivedExample;
}

B.cpp

{
class DerivedExample : public Example {
//How to override the functions of class Base here?
}
}

我有一个接收Base参数的方法:

void doSomething(Base* base) = 0;

问题是,这种doSomething方法只接受Example但不接受DerivedExample。我该怎么做才能让A的头文件知道类Example是类Base的派生类,而无需将所有方法定义移动到那里?对不起,如果听起来模棱两可,我对C++很陌生。谢谢。

在各自的HPP文件中定义类,当你编写函数的主体时,你必须将它们定义为 派生示例::d oSomething() <- 如果这是一个函数, 并且您必须在.cpp文件中包含相应的HPP文件 如果我正确理解了您的 QS。那么他们不会有任何歧义

我正在附加我的示例添加多个文件程序代码。 类似地定义继承类,后跟所谓的函数。

header.hpp
#ifndef HEADER_HPP
#define HEADER_HPP
class Addition
{
public :
int sum(int a ,int b);
};
#endif

function.cpp
#include"header.hpp"
int Addition::sum(int a,int b)
{
//int a,b,result;
//result=a+b;
return a+b;
}
main.cpp
#include<iostream>
using namespace std;
#include"header.hpp"
int main()
{
int a,b,result;
Addition add;
cout<<"enter the first number ";
cin>>a;
cout<<"enter the second number";
cin>>b;
result=add.sum(a,b);
cout<<"the sum of the two numbers is "<<result;
return 0;
}