【发布时间】: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*。
编辑
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
【问题讨论】:
-
请发布更多您的代码。另外,只是猜测,因为代码没有显示,但在
Human类定义的末尾添加一个分号 (;) ;) -
请提供完整的示例,如here所述。
-
我编辑并发布了上面的代码
标签: c++ inheritance interface