在C++中使用带有接口类的实现的正确方法是什么

What is a correct way of using an implementation with an interface class in C++?

本文关键字:实现 是什么 方法 接口 C++      更新时间:2023-10-16

我有一个类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++中,你可以实现一些函数,但这不是一个接口(也称为纯虚拟或抽象类(,而是一个虚拟类(仍然无法安装,但不是那么抽象,因此它们可以被视为接口(