我有一个类 Child
和一个类 Human
,其中 Human
具有在 Child
中声明的所有函数虚函数。并且 Child
类继承自 Human
类。
我想使用 Human
作为接口(interface)文件来隐藏 Child
中的实现。
我并没有真正设置构造函数,而是设置了一个初始化基本设置的 init()
函数。
现在,我可以使用 Human
接口(interface)文件来使用 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 会自动引入
human.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;
}
关于c++ - 在 C++ 中使用带有接口(interface)类的实现的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6767862/