如何在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# 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();
其他回答
在Managed c++中,静态类语法是:-
public ref class BitParser abstract sealed
{
public:
static bool GetBitAt(...)
{
...
}
}
... 迟到总比不到好……
在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
与其他托管编程语言不同,“静态类”在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();
你也可以在命名空间中创建一个自由函数:
在BitParser.h
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex);
}
在BitParser.cpp
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex)
{
//get the bit :)
}
}
一般来说,这是编写代码的首选方式。当不需要对象时,不要使用类。