I have a class Child
and a class Human
where Human
has all the functions declared in Child
as virtual functions. 开发者_Python百科And a class Child
inherits from Human
class.
I want to use Human
as a interface file to hide implementation in Child
.
I didn't really set up a constructor, but I set up an init()
function which initializes basic settings.
Now, what is a good way that I can use Child
functions using Human
interface file?
I tried
Human *John = new Child();
but I got the following errors.
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
I don't understand where int*
came from either. None of my functions declared returns int*.
edit
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()
{
}
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
You need to #include "Child.h"
in your cpp
file. You can do this along with including human.h
or you can not include human.h
as that will be brought in automatically by the include within 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;
}
You don't have the definition for the Child class in your main.cpp. Most probably you included Human.h:
#include "human.h"
instead of Child.h:
#include "child.h"
But that's a guess. What is certain is that the code that includes the definiton of the Child class is not available in the Main.cpp at the point where you have the error. This could be due to wrong or missing #include or missuse of the #ifdef precompiler directives. But to be able to better help you we need more of the code like the declaration of "Child.h" and "Human.h" and the full code of the "Main.cpp".
For the interface part. To have a truly clean interface you should not implement any function in it. That's the best practice in using interfaces. In C++ you can implement some of the functions but that would not be an interface (aka as pure virtual or abstract class) but a virtual class (which still can't be instatiated but are not that abstract so that they can be considered interfaces)
精彩评论