c++ - 尝试进行多态性时出现 c2011 错误 c++

标签 c++ polymorphism

我正在尝试通过我的图像处理程序实现多态性。我一直收到这个错误,我认为这是因为我在头文件和 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 文件这两个不同的文件中声明了 Scale 类。实际上,如果您在缩放功能中创建新图像,我不知道为什么要使用继承。

你的 header ,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;
}

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

关于c++ - 尝试进行多态性时出现 c2011 错误 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47841386/

相关文章:

java - java中动态多态性的实时示例是什么

c++ - 重载运算符[]多态

c++ - 将 char 数组分配给单个 char 的奇怪行为

c++ - 错误 C2061 : syntax error : identifier

c++ - vector 中的移动元素未按预期工作

swift - 在运行时,Swift 如何知道要使用哪个实现?

polymorphism - 我可以使用 pa_monad 来确保 η 扩展吗?

c++ - 继承类中的 shared_from_this() 类型错误(是否有 dyn.type-aware 共享指针?)

c++ - BoldDays 与 TMonthCalendar

c++ - 无法从派生指针访问公共(public)基成员