C2011错误C 试图进行多态性

c2011 error c++ when trying to do polymorphism

本文关键字:多态性 错误 C2011      更新时间:2023-10-16

我正在尝试通过我的图像操纵程序实现多态性。我一直遇到此错误,我认为这是由我在标题文件和CPP文件中两次定义scale引起的。

Error   C2011   'scale': 'class' type redefinition  

我不确定该怎么办。感谢您的任何帮助。

.cpp文件

   Image *begin= new Image(750, 750);
   begin->read("picture1.jpg");
   Image *enlarged= new Image(1500, 1500);
    scale *pass= new scale(*imgScale);
    pass->manipulator(1500, 1500);
    pass->load("manipulated.jpg");
    class scale : public Image
    {
    public:    
        scale(Image const &firstimg)
        {
             w = firstimg.w;
             h = firstimg.h;
            pixels = firstimg.pixels;
        }
        void manipulator(int w2, int h2)
        {
            Image *temp = new Image(w2, h2);
            float x_ratio = (float )w / w2;
            float y_ratio = (float )h / h2;
            float px, py;
            for (int i = 0; i < h2; i++)
            {
                for (int j = 0; j < w2; j++)
                {
                    px = floor(j*x_ratio);
                    py = floor(i*y_ratio);
                    temp->pixels[(i*w2) + j] = this->pixels[(int)((py*w) + px)];
                }
            }
        }    
};

标题文件

#pragma once    
#ifndef manipulator_H
#define manipulator_H
class scale : public Image
{
    public:
        scale(Image const &firstimg);
        void manipulator(int w2, int h2);
};
#endif

您在两个不同的文件中声明您的类规模,在算法标题文件和.cpp文件中。实际上,如果您在Zoom函数中创建新图像,我不知道为什么如何使用继承。

您的标题,scale.h应该是这样的:

#pragma once    
#ifndef ALGORITHMS_H
#define ALGORITHMS_H
class Image;    
class Scale {
    public:
        explicit Scale(Image const &beginImg);
        void zoom(int w2, int h2);
    private:
    // Here all your private variables
    int w;
    int h;
    ¿? pixels;
};
#endif

和您的CPP文件,scale.cpp:

#include "scale.h"
#include "image.h"
Scale::Scale(Image const &beginImg) : 
        w(beginImg.w),
        h(beginImg.h),
        pixels(beginImg.pixels) {}
void Scale::zoom(int w2, int h2){
       Image *temp = new Image(w2, h2);
       double x_ratio = (double)w / w2;
       double y_ratio = (double)h / h2;
       double px, py;
       // rest of your code;
}  

,然后在您要使用此类的地方,示例您的主要内容:

int main() {
    Image *imgScale = new Image(750, 750);
    imgScale->readPPM("Images/Zoom/zIMG_1.ppm");
    Scale *test = new Scale(*imgScale);
    test->zoom(1500, 1500);
    test->writePPM("Scale_x2.ppm");
    delete imgScale;
    delete test;
    return 0;
}

无论如何,请考虑使用智能指针代替原始指针,并查看我所做的不同修改。