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

时间:2011-07-20 20:10:17

标签: c++ inheritance interface

我有一个班级Child和一个班级Human,其中HumanChild中声明的所有函数作为虚函数。类Child继承自Human类。

我想使用Human作为接口文件来隐藏Child中的实现。

我没有真正设置构造函数,但我设置了init()函数来初始化基本设置。

现在,使用Child接口文件可以使用Human函数的好方法是什么?

我试过

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

2 个答案:

答案 0 :(得分:7)

您需要在#include "Child.h"文件中cpp。您可以执行此操作以及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; }
{{1}}

答案 1 :(得分:2)

您的main.cpp中没有Child类的定义。很可能你包括了Human.h:

#include "human.h"

而不是Child.h:

#include "child.h"

但这是猜测。可以肯定的是,包含Child类定义的代码在您遇到错误时Main.cpp中不可用。这可能是由于错误或缺少#include或错过#ifdef预编译器指令。但为了能够更好地帮助您,我们需要更多的代码,如“Child.h”和“Human.h”的声明以及“Main.cpp”的完整代码。

用于界面部分。要拥有一个真正干净的界面,您不应该在其中实现任何功能。这是使用接口的最佳实践。在C ++中,你可以实现一些函数但不是一个接口(也就是纯虚拟或抽象类),而是一个虚拟类(它仍然不能被实例化但不是那么抽象,所以它们可以被认为是接口)