【问题标题】:Create a class with static and friend methods C++使用静态和友元方法创建一个类 C++
【发布时间】:2015-05-21 10:02:16
【问题描述】:

为什么要创建一个只有静态和友元方法的类?

例如:

namespace Image
{
    GLuint LoadImage(std::string name);
    GLuint LoadImage(std::string name, const int min, const int mag, const int wrapx, const int wrapy);
    GLuint LoadImage(std::string name, unsigned int& width, unsigned int& height);
    unsigned char* LoadImageData(std::string name, unsigned int& width, unsigned int& height);
    class ImagePrivate
    {
        static ILuint DevilLoadImage(std::string name);
        friend GLuint LoadImage(std::string name);
        friend GLuint LoadImage(std::string name, const int min, const int mag, const int wrapx, const int wrapy);
        friend GLuint LoadImage(std::string name, unsigned int& width, unsigned int& height);
        friend unsigned char*  LoadImageData(std::string name, unsigned int& width, unsigned int& height, unsigned int& bpp);
    };
}

友元方法使用 ImagePrivate::DevilLoadImage。

如果你已经有一个命名空间(图片),你为什么要创建一个类?我以为一个类是用来创建对象的,但在这种情况下,并没有创建任何对象。

非常感谢!

【问题讨论】:

  • 例如,您不能将命名空间作为模板参数传递...命名空间更像是一个静态概念(编译时),而不是作为虚拟表存在的类。
  • @Jean-BaptisteYunès:只有多态类“有某种存在”作为运行时元数据。这个类不是多态的。

标签: c++ static-methods friend


【解决方案1】:

如果你已经有一个命名空间(图片),你为什么要创建一个类?

似乎正在将DevilLoadImage设为私有,因此它只能由命名空间中的“公共”函数调用。

这是否明智是一个品味问题。替代方法是将内部函数放在“详细信息”命名空间中,将它们隐藏在源文件中(这可能不是模板的选项),或者记录它们不用于一般用途。

我认为类是用来创建对象的

这当然是最常见的用途。但它也定义了一个范围(如命名空间)并允许您指定成员的可访问性(与命名空间不同),因此可以将其用于此目的。

【讨论】:

  • 感谢您的回答!为什么不在 Image 命名空间内创建命名空间?那会不一样吗?
  • @J.PG:命名空间不能有私有成员。这段代码的目的似乎是通过将 DevilLoadImage 设为私有成员来防止除指定函数之外的任何东西使用它。为此,您需要一个类,而不是命名空间。
猜你喜欢
  • 2016-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多