如何在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#中一样,那么如果不使用Managed c++,您将无法做到这一点。
但是从示例的外观来看,您只需要在BitParser对象上创建一个公共静态方法。像这样:
BitParser.h
class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);
// ...lots of great stuff
private:
// Disallow creating an instance of this object
BitParser() {}
};
BitParser.cpp
bool BitParser::getBitAt(int buffer, int bitIndex)
{
bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}
您可以使用此代码以与示例代码相同的方式调用该方法。
其他回答
在c++中,你需要创建一个类的静态函数(不是静态类)。
class BitParser {
public:
...
static ... getBitAt(...) {
}
};
然后,您应该能够使用BitParser::getBitAt()调用函数,而无需实例化一个对象,我认为这是期望的结果。
在c++中你“可以”有一个静态类,正如前面提到的,静态类是一个没有实例化它的任何对象的类。在c++中,可以通过将构造函数/析构函数声明为private来获得。结果是一样的。
正如这里所指出的,在c++中实现这一点的更好方法可能是使用名称空间。但是因为没有人在这里提到最后一个关键字,所以我在这里发布的是c#中直接等价的静态类在c++ 11或更高版本中的样子:
class BitParser final
{
public:
BitParser() = delete;
static bool GetBitAt(int buffer, int pos);
};
bool BitParser::GetBitAt(int buffer, int pos)
{
// your code
}
如果您正在寻找一种将“static”关键字应用到类的方法,就像在c#中一样,那么如果不使用Managed c++,您将无法做到这一点。
但是从示例的外观来看,您只需要在BitParser对象上创建一个公共静态方法。像这样:
BitParser.h
class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);
// ...lots of great stuff
private:
// Disallow creating an instance of this object
BitParser() {}
};
BitParser.cpp
bool BitParser::getBitAt(int buffer, int bitIndex)
{
bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}
您可以使用此代码以与示例代码相同的方式调用该方法。
在Managed c++中,静态类语法是:-
public ref class BitParser abstract sealed
{
public:
static bool GetBitAt(...)
{
...
}
}
... 迟到总比不到好……