如何在c++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
假设我创建了BitParser类。BitParser类定义是什么样子的?
如何在c++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
假设我创建了BitParser类。BitParser类定义是什么样子的?
当前回答
你也可以在命名空间中创建一个自由函数:
在BitParser.h
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex);
}
在BitParser.cpp
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex)
{
//get the bit :)
}
}
一般来说,这是编写代码的首选方式。当不需要对象时,不要使用类。
其他回答
在c++中没有静态类这样的东西。最接近的近似是只包含静态数据成员和静态方法的类。 类中的静态数据成员由所有类对象共享,因为不管类的对象有多少,它们在内存中只有一个副本。 类的静态方法可以访问所有其他静态成员、静态方法和类外的方法
在c++中,你需要创建一个类的静态函数(不是静态类)。
class BitParser {
public:
...
static ... getBitAt(...) {
}
};
然后,您应该能够使用BitParser::getBitAt()调用函数,而无需实例化一个对象,我认为这是期望的结果。
你也可以在命名空间中创建一个自由函数:
在BitParser.h
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex);
}
在BitParser.cpp
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex)
{
//get the bit :)
}
}
一般来说,这是编写代码的首选方式。当不需要对象时,不要使用类。
与其他托管编程语言不同,“静态类”在c++中没有任何意义。可以使用静态成员函数。
在c++中实现“不能被实例化的类”行为的一种(众多)替代方法,但也是最优雅的(在我看来)方法(与使用名称空间和私有构造函数来模拟静态行为相比)是声明一个带有私有访问修饰符的虚拟纯虚函数。
class Foo {
public:
static int someMethod(int someArg);
private:
virtual void __dummy() = 0;
};
如果使用c++ 11,可以在类声明中使用final说明符来限制其他类继承它,从而确保类不被继承(以纯粹模拟静态类的行为)。
// C++11 ONLY
class Foo final {
public:
static int someMethod(int someArg);
private:
virtual void __dummy() = 0;
};
尽管听起来很傻很不合逻辑,但c++ 11允许声明一个“不能被重写的纯虚函数”,你可以使用它来声明类final来完全实现静态行为,因为这会导致生成的类不可继承,虚函数也不能以任何方式被重写。
// C++11 ONLY
class Foo final {
public:
static int someMethod(int someArg);
private:
// Other private declarations
virtual void __dummy() = 0 final;
}; // Foo now exhibits all the properties of a static class