如何在c++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
假设我创建了BitParser类。BitParser类定义是什么样子的?
如何在c++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
假设我创建了BitParser类。BitParser类定义是什么样子的?
当前回答
如果你正在寻找一种将“static”关键字应用到类的方法,就像在c#中一样
静态类只是编译器牵着你的手,阻止你编写任何实例方法/变量。
如果你只是写一个普通的类,没有任何实例方法/变量,这是一样的,这就是你在c++中所做的
其他回答
我能写类似静态类的东西吗?
不,根据c++ 11 N3337标准草案附件C 7.1.1:
Change: In C ++, the static or extern specifiers can only be applied to names of objects or functions. Using these specifiers with type declarations is illegal in C ++. In C, these specifiers are ignored when used on type declarations. Example: static struct S { // valid C, invalid in C++ int i; }; Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C ++, class members can be declared with the static storage class specifier. Allowing storage class specifiers on type declarations could render the code confusing for users.
和struct一样,class也是一种类型声明。
通过遍历附件A中的语法树也可以得出同样的结论。
有趣的是,静态结构在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 :)
}
}
一般来说,这是编写代码的首选方式。当不需要对象时,不要使用类。
在c++中没有静态类这样的东西。最接近的近似是只包含静态数据成员和静态方法的类。 类中的静态数据成员由所有类对象共享,因为不管类的对象有多少,它们在内存中只有一个副本。 类的静态方法可以访问所有其他静态成员、静态方法和类外的方法
class A final {
~A() = delete;
static bool your_func();
}
Final意味着一个类不能被继承。
析构函数的Delete意味着不能创建此类的实例。
此模式也称为“util”类。
正如许多人所说,静态类的概念在c++中并不存在。
在这种情况下,首选的解决方案是包含静态函数的规范名称空间。
与其他托管编程语言不同,“静态类”在c++中没有任何意义。可以使用静态成员函数。