如何在c++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
假设我创建了BitParser类。BitParser类定义是什么样子的?
如何在c++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
假设我创建了BitParser类。BitParser类定义是什么样子的?
当前回答
与其他托管编程语言不同,“静态类”在c++中没有任何意义。可以使用静态成员函数。
其他回答
正如这里所指出的,在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
}
与其他托管编程语言不同,“静态类”在c++中没有任何意义。可以使用静态成员函数。
名称空间对于实现“静态类”可能不太有用的一种情况是使用这些类实现继承上的组合。名称空间不能是类的友元,因此不能访问类的私有成员。
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;
}
};
这类似于c#在c++中的实现方式
在c# file.cs中,你可以在公共函数中使用私有变量。 当在另一个文件中,你可以通过调用命名空间的函数来使用它,如下所示:
MyNamespace.Function(blah);
下面是如何在c++中对相同的对象进行imp:
SharedModule.h
class TheDataToBeHidden
{
public:
static int _var1;
static int _var2;
};
namespace SharedData
{
void SetError(const char *Message, const char *Title);
void DisplayError(void);
}
SharedModule.cpp
//Init the data (Link error if not done)
int TheDataToBeHidden::_var1 = 0;
int TheDataToBeHidden::_var2 = 0;
//Implement the namespace
namespace SharedData
{
void SetError(const char *Message, const char *Title)
{
//blah using TheDataToBeHidden::_var1, etc
}
void DisplayError(void)
{
//blah
}
}
OtherFile。h
#include "SharedModule.h"
OtherFile.cpp
//Call the functions using the hidden variables
SharedData::SetError("Hello", "World");
SharedData::DisplayError();
在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