c++ 父类成员函数的参数中有子类类型的对象 (前置声明解决)

来源:互联网 发布:杰里米·兰姆数据 编辑:程序博客网 时间:2024/05/06 04:21

父类Matrix  子类Image ;显然在子类的头文件Image.h中要包含进父类的的头文件Matrix.h,但在 父类成员函数的参数中有子类类型的对象 时,参数中的Image类型对象提示为未知的类型,但如果将Image.h 包含进Matrix.h中会提示:“Matrix”: 未定义基类  这种相互包含的错误

//Matrix.h#ifndef Matrix_H#define Matrix_H//#include"Image.h"  会出现互相包含的错误!</span></span>class Image;//前置引用class Matrix{public:Matrix();Matrix(int h,int w);Matrix(int h, int w, double val);Matrix(const Matrix &m);~Matrix();Matrix operator*(const Image &img);  //两幅尺寸相同的图像,对应像素点的数值相乘;Matrix operator/(const Image &img);  //两幅尺寸相同的图像,对应像素点的数值相除;</span>protected:int height;int width;double **data;};#endif
//Image.h#ifndef Image_H#define Image_H#include "Matrix.h"class Image : public Matrix{public:Image(); //构造函数,创建行列都为零的Image对象Image(int h, int w); //构造函数重载,创建h行,w列的Image对象};#endif
//Matrix.cpp#include"Matrix.h"#include"Image.h"</span>Matrix::Matrix()//无参的构造函数{height=0;width=0;data=NULL;}Matrix::Matrix(int h,int w)//两个参数的构造函数{height=h;width=w;data=new double *[height];for(int i=0;i<height;i++){data[i]=new double [width];}}


解决方法:使用前置引用(声明)。即在父类的头文件Matrix.h中进行下子类的声明(class Image;)并且在父类的实现文件Matrix.cpp中包含进子类的头文件Image.h.


最后,贴上一片关于前置声明的很好的一片博文:http://blog.csdn.net/yunyun1886358/article/details/5672574


1 0
原创粉丝点击