【问题标题】:Class and a lot of functions that can access it's private data类和许多可以访问它的私有数据的函数
【发布时间】:2013-09-08 18:05:29
【问题描述】:

我正在编写一个 C++ 程序,该程序读取一个 .bmp 文件并创建一个动态 2D 像素数组[1],它代表图像。该信息存储在 Image[2] 类实例中。

所以,我希望有一些函数可以对图像应用一些颜色效果,但我只希望这些函数能够访问 Image 的私有变量。

Image 类必须能够在没有颜色效果的情况下工作,因此它们不能是类的函数(内联),但 Image 类也没有任何 getter 或 setter。我想到了一个朋友函数,但这意味着我必须手动列出每个函数。如果有人能帮助我解决我的问题,我将不胜感激!

[1]

struct Pixel
{
    unsigned char Red;
    unsigned char Blue;
    unsigned char Green;
    unsigned char Unused;
};

[2]

class Image
{
public:
    Image();
    ~Image();

    bool Open(char*);
    void Close();
    bool Save();

private:
    bool good;
    Pixel** loadedImage;
    char* filePath;
};

【问题讨论】:

  • 好吧,如果所有这些函数都是某个类的(可能是静态的)成员,那么您可以让整个类成为朋友,如friend class ColorEffects;

标签: c++ class private


【解决方案1】:

似乎最明智的做法是创建一个具有静态成员的类,然后使该类成为 Image 的朋友类。所以,例如,

class Bitmap {
    ...
    friend class ImageHandler;
}

class ImageHandler {
    static void Manipulate();
}

void ImageHandler::Manipulate() {
    // now you can access all of the private vars of Pixel.
}

void Pixel::SomeFunction() {
    ImageHandler::Manipulate();
}

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 2011-08-04
    • 2015-04-12
    • 1970-01-01
    • 2016-01-20
    • 2021-07-23
    相关资源
    最近更新 更多