Fla*_*nix 3 c++ polymorphism inheritance
最近我试图解决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
Run Code Online (Sandbox Code Playgroud)
这是我的"祖父"标题,名为"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
Run Code Online (Sandbox Code Playgroud)
现在,在一个名为White_Black_Mandel_Imp1.cpp的单独文件中执行Black_White_Mandel标头:
#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
}
Run Code Online (Sandbox Code Playgroud)
因此,Mandel.h必须实现2个函数,因为它们是虚拟的并且"= 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的精确副本,但还有一些额外的东西,但这对我来说真的很愚蠢,这没有任何意义.
我究竟做错了什么?
虽然您的祖先类中有2个纯虚方法,但这并不意味着它们的原型可以在子类中使用.
您必须在您的子类中声明原型:
class Black_White_Mandel: public Mandel {
public:
virtual void compute("various arguments")
protected:
int max_iterations; //a specific variable of this Black_White Version
private:
virtual int compute_point("various arguments");
};
Run Code Online (Sandbox Code Playgroud)
该virtual关键字是可选的,但它是有用的知道,该方法的确是虚拟的.你没有被迫在这个特定的子类中实现它们,你可以避免指定任何东西,但你仍然有两个必须实现的纯虚方法,所以你将无法实例化这个子类的任何对象(你将有无论如何在层次结构树中实现它们.
虚拟析构函数是必需的,否则在类似的情况下:
Base *derived = new Derived();
delete derived;
Run Code Online (Sandbox Code Playgroud)
编译器无法调用正确的析构函数.
| 归档时间: |
|
| 查看次数: |
744 次 |
| 最近记录: |