最近我尝试解决 C++ 继承和多态性,但我遇到了一些对我来说毫无意义的问题。我在单独的文件中有 2 个标头和一个带有实现的 cpp 文件。我的代码的简短摘要如下:
#ifndef MANDEL_H_
#define MANDEL_H_
class Mandel{
public:
virtual void compute("various arguments") = 0;
//dummy destructor, I must have one or compile is sad and I dunno why
virtual ~Mandel();
private:
virtual int compute_point("various arguments") = 0;
};
#endif
这是我的“祖父”标题,名为“Mandel.h”。现在转到“父亲”标题。下一个标题指定了一些特定于 Mandel 的白色和黑色实现的变量,称为“Black_White_Mandel.h”:
#ifndef BLACK_WHITE_MANDEL_H_
#define BLACK_WHITE_MANDEL_H_
#include "Mandel.h"
class Black_White_Mandel: public Mandel {
protected:
int max_iterations; //a specific variable of this Black_White Version
};
#endif
现在遵循 Black_White_Mandel 标头的实现,在一个名为 White_Black_Mandel_Imp1.cpp 的单独文件中:
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "Mandel.h"
#include "Black_White_Mandel.h"
using namespace std;
//constructor
Black_White_Mandel::Black_White_Mandel(){
max_iterations = 255;
}
//destructor
Black_White_Mandel::~Black_White_Mandel(){}
int Black_White_Mandel::compute_point("various arguments") {
//code and stuff
return 0;
}
void Black_White_Mandel::compute("various arguments") {
//code and stuff
}
因此,Mandel.h 有两个必须实现的功能,因为它们是虚拟的并且“=0”。在 White_Black_Mandel_Imp1.cpp 中,当我实现编译器发疯的那些函数时。它说函数没有在 White_Black_Mandel.h 中定义,虽然这是真的,但它们是在 Mandel.h 中定义的。因此,通过继承,White_Black_Mandel_Imp1.cpp 应该知道它有义务从 Mandel.h 实现这些功能。
我不明白,我的一个朋友说我的 White_Black_Mandel.h 文件应该是 Mandel.h 的精确副本,但还有一些额外的东西,但这对我来说真的很愚蠢,没有任何意义。
我究竟做错了什么?