MST
星途 面试题库

面试题:C++类普通成员函数的功能设计之性能优化与设计模式

考虑一个C++类 `ImageProcessor`,用于处理图像数据。该类有成员变量表示图像的宽度 `width`、高度 `height` 以及一个大的 `unsigned char` 数组存储图像像素数据。设计一个普通成员函数 `applyFilter`,它接受一个滤波算法的类型作为参数(例如高斯滤波、均值滤波等),对图像应用相应的滤波算法。要求在函数设计中考虑性能优化,例如如何高效地访问像素数据,并且运用合适的设计模式(如策略模式)来管理不同的滤波算法,使得代码具有良好的扩展性和维护性。
35.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <memory>

// 抽象滤波算法类
class FilterStrategy {
public:
    virtual void applyFilter(unsigned char* pixels, int width, int height) = 0;
    virtual ~FilterStrategy() = default;
};

// 高斯滤波策略类
class GaussianFilter : public FilterStrategy {
public:
    void applyFilter(unsigned char* pixels, int width, int height) override {
        // 高斯滤波算法实现
        std::cout << "Applying Gaussian Filter" << std::endl;
    }
};

// 均值滤波策略类
class MeanFilter : public FilterStrategy {
public:
    void applyFilter(unsigned char* pixels, int width, int height) override {
        // 均值滤波算法实现
        std::cout << "Applying Mean Filter" << std::endl;
    }
};

class ImageProcessor {
private:
    int width;
    int height;
    std::unique_ptr<unsigned char[]> pixels;

public:
    ImageProcessor(int w, int h) : width(w), height(h), pixels(std::make_unique<unsigned char[]>(w * h * 3)) {}

    void applyFilter(const std::unique_ptr<FilterStrategy>& strategy) {
        strategy->applyFilter(pixels.get(), width, height);
    }
};

使用示例:

int main() {
    ImageProcessor processor(100, 100);
    std::unique_ptr<FilterStrategy> gaussian = std::make_unique<GaussianFilter>();
    processor.applyFilter(gaussian);

    std::unique_ptr<FilterStrategy> mean = std::make_unique<MeanFilter>();
    processor.applyFilter(mean);

    return 0;
}

解释

  1. 策略模式:定义了抽象的 FilterStrategy 类,具体的滤波算法如 GaussianFilterMeanFilter 继承自该抽象类,并实现 applyFilter 方法。
  2. 性能优化:使用 std::unique_ptr<unsigned char[]> 来存储图像像素数据,提高内存管理效率,同时在 applyFilter 函数中直接传递数组指针来高效访问像素数据。
  3. 扩展性和维护性:通过策略模式,新增滤波算法只需要继承 FilterStrategy 并实现 applyFilter 方法,在 ImageProcessorapplyFilter 函数中可以方便地使用新的滤波策略。