use*_*594 2 c++ inheritance interface
我有一个类Child和一个类Human,其中Human所有函数都声明Child为虚函数.并且一个类Child继承自Human类.
我想Human用作接口文件来隐藏实现Child.
我没有真正设置构造函数,但我设置了一个init()初始化基本设置的函数.
现在,有什么方法可以使用接口文件来使用Child函数Human?
我试过了
Human *John = new Child();
Run Code Online (Sandbox Code Playgroud)
但是我遇到了以下错误.
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
Run Code Online (Sandbox Code Playgroud)
我不明白从哪里来的int*.我的所有函数都没有返回int*.
编辑
main.cpp中
#include <stdlib.h>
#include <stdio.h>
#include "Human.h"
using namespace std;
int main(){
Human *John = new Child();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
human.h
#ifndef __HUMAN_h__
#define __HUMAN_h__
class Human
{
public:
virtual void Init() = 0;
virtual void Cleanup() = 0;
};
#endif
Run Code Online (Sandbox Code Playgroud)
Child.h
#ifndef __CHILD_h__
#define __CHILD_h__
#include "Human.h"
class Child : public Human
{
public:
void Init();
void Cleanup();
};
#endif
Run Code Online (Sandbox Code Playgroud)
Child.cpp
#include "Child.h"
void Child::Init()
{
}
void Child::Cleanup()
{
}
Run Code Online (Sandbox Code Playgroud)
Makefile文件
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
Run Code Online (Sandbox Code Playgroud)
您需要#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;
}
Run Code Online (Sandbox Code Playgroud)