如何在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++ 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编程中使用静态结构?
这类似于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();
名称空间对于实现“静态类”可能不太有用的一种情况是使用这些类实现继承上的组合。名称空间不能是类的友元,因此不能访问类的私有成员。
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++中,你需要创建一个类的静态函数(不是静态类)。
class BitParser {
public:
...
static ... getBitAt(...) {
}
};
然后,您应该能够使用BitParser::getBitAt()调用函数,而无需实例化一个对象,我认为这是期望的结果。
与其他托管编程语言不同,“静态类”在c++中没有任何意义。可以使用静态成员函数。