【问题标题】:What is a correct way of using an implementation with an interface class in C++?在 C++ 中使用接口类的实现的正确方法是什么?
【发布时间】:2011-07-20 20:10:17
【问题描述】:

我有一个类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*。

编辑

ma​​in.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

【问题讨论】:

  • 请发布更多您的代码。另外,只是猜测,因为代码没有显示,但在 Human 类定义的末尾添加一个分号 (;) ;)
  • 请提供完整的示例,如here所述。
  • 我编辑并发布了上面的代码

标签: c++ inheritance interface


【解决方案1】:

您需要在您的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;
}

【讨论】:

  • Re“这不再是必要的,因为 child.h 包含它”:我倾向于对这类事情持迂腐态度。如果我的代码使用来自 Human.h 的构造,我会 #include "Human.h" 即使我知道 Child.h 必须执行相同的 #include。
【解决方案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++ 中,您可以实现一些功能,但这不是接口(也称为纯虚拟或抽象类),而是虚拟类(仍然不能被实例化但不是那么抽象,因此它们可以被视为接口)

【讨论】:

  • 你在我还在写答案的时候发布了代码:)
  • 只选择一个答案是一个很好的限制。只要问题得到解决,我不介意其他人的答案得到批准:)但感谢您的评论;)
猜你喜欢
  • 2022-01-17
  • 2021-03-26
  • 1970-01-01
  • 2021-10-15
  • 2013-01-01
  • 2016-07-03
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
相关资源
最近更新 更多