在C++中使用带有接口类的实现的正确方法是什么
What is a correct way of using an implementation with an interface class in C++?
我有一个类Child
和一个类Human
,其中Human
具有在Child
中声明为虚拟函数的所有函数。并且类Child
继承自Human
类。
我想使用Human
作为接口文件来隐藏Child
中的实现。
我并没有真正设置构造函数,但我设置了一个init()
函数来初始化基本设置。
现在,使用Human
接口文件使用Child
函数的好方法是什么?
我试过
Human *John = new Child();
但我犯了以下错误。
main.cpp:7: error: expected type-specifier before ‘Child’
main.cpp:7: error: cannot convert ‘int*’ to ‘Human*’ in initialization
main.cpp:7: error: expected ‘,’ or ‘;’ before ‘Child
我也不明白int*
是从哪里来的。我声明的函数中没有一个返回int*。
编辑
main.cpp
#include <stdlib.h>
#include <stdio.h>
#include "Human.h"
using namespace std;
int main(){
Human *John = new Child();
return 0;
}
human.h
#ifndef __HUMAN_h__
#define __HUMAN_h__
class Human
{
public:
virtual void Init() = 0;
virtual void Cleanup() = 0;
};
#endif
Child.h
#ifndef __CHILD_h__
#define __CHILD_h__
#include "Human.h"
class Child : public Human
{
public:
void Init();
void Cleanup();
};
#endif
Child.cpp
#include "Child.h"
void Child::Init()
{
}
void Child::Cleanup()
{
}
生成文件
CC = g++
INC = -I.
FLAGS = -W -Wall
LINKOPTS = -g
all: program
program: main.o Child.o
$(CC) -Wall -o program main.o Child.o
main.o: main.cpp Human.h
$(CC) -Wall -c main.cpp Human.h
Child.o: Child.cpp Child.h
$(CC) -Wall -c Child.cpp Child.h
Child.h: Human.h
clean:
rm -rf program
您需要在cpp
文件中使用#include "Child.h"
。您可以在包含human.h
的同时执行此操作,也可以不包含human.h
,因为child.h
中的包含会自动带入
#include <stdlib.h>
#include <stdio.h>
#include "Child.h"
#include "Human.h" // This is no longer necessary, as child.h includes it
using namespace std;
int main(){
Human *John = new Child();
return 0;
}
您的main.cpp中没有Child类的定义。很可能您包含了Human.h:
#include "human.h"
而不是Child.h:
#include "child.h"
但这只是猜测。可以肯定的是,在出现错误时,包含Child类定义的代码在Main.cpp中不可用。这可能是由于#ifdef预编译器指令的错误或丢失#include或使用不当。但为了更好地帮助您,我们需要更多的代码,如"Child.h"answers"Human.h"的声明以及"Main.cpp"的完整代码。
对于接口部分。要有一个真正干净的接口,你不应该在其中实现任何功能。这是使用接口的最佳实践。在C++中,你可以实现一些函数,但这不是一个接口(也称为纯虚拟或抽象类(,而是一个虚拟类(仍然无法安装,但不是那么抽象,因此它们可以被视为接口(
相关文章:
- 实现无开销push_back的最佳方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 在 c++ 或 python 中生成一个体面的视差图以在 Raspberry Pi 上实现的最佳方法(算法或函数)是什么
- 在 C++17 中实现迭代器和const_iterator的正确方法是什么?
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 实现此自定义priority_queue的正确方法是什么
- 实现此"on error, throw"回调的最佳方法是什么?
- 在QGraphicsView上实现交互式样条曲线的最佳方法是什么?
- 当您知道结构将来会更改时,实现结构读写的最佳方法是什么
- std :: is_nothrow_copy_copy_constructible的实现是什么?
- 具有多态数据的容器的常见实现是什么
- RWTPtrOrderedVector的替代实现是什么
- 将一元函数应用于向量的某些元素的良好实现是什么?
- 向量类中擦除函数的正确实现是什么
- 映射到ASCII的Character的底层实现是什么?
- c++中标准的延迟/终结器实现是什么?
- 访问和更改长布尔数组的最快实现是什么?
- 单例类的确切用法和实现是什么?