如何在c++中创建静态类?我应该可以这样做:

cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;

假设我创建了BitParser类。BitParser类定义是什么样子的?


当前回答

名称空间对于实现“静态类”可能不太有用的一种情况是使用这些类实现继承上的组合。名称空间不能是类的友元,因此不能访问类的私有成员。

class Class {
 public:
  void foo() { Static::bar(*this); }    

 private:
  int member{0};
  friend class Static;
};    

class Static {
 public:
  template <typename T>
  static void bar(T& t) {
    t.member = 1;
  }
};

其他回答

在Managed c++中,静态类语法是:-

public ref class BitParser abstract sealed
{
    public:
        static bool GetBitAt(...)
        {
            ...
        }
}

... 迟到总比不到好……

class A final {
  ~A() = delete;
  static bool your_func();
}

Final意味着一个类不能被继承。

析构函数的Delete意味着不能创建此类的实例。

此模式也称为“util”类。

正如许多人所说,静态类的概念在c++中并不存在。

在这种情况下,首选的解决方案是包含静态函数的规范名称空间。

在c++中你“可以”有一个静态类,正如前面提到的,静态类是一个没有实例化它的任何对象的类。在c++中,可以通过将构造函数/析构函数声明为private来获得。结果是一样的。

如果你正在寻找一种将“static”关键字应用到类的方法,就像在c#中一样

静态类只是编译器牵着你的手,阻止你编写任何实例方法/变量。

如果你只是写一个普通的类,没有任何实例方法/变量,这是一样的,这就是你在c++中所做的

你也可以在命名空间中创建一个自由函数:

在BitParser.h

namespace BitParser
{
    bool getBitAt(int buffer, int bitIndex);
}

在BitParser.cpp

namespace BitParser
{
    bool getBitAt(int buffer, int bitIndex)
    {
        //get the bit :)
    }
}

一般来说,这是编写代码的首选方式。当不需要对象时,不要使用类。