C ++中接口的静态类的良好用法

时间:2014-06-05 11:14:24

标签: c++ interface

我正在为某些只更改某些HW寄存器的驱动程序创建API。我曾经想过使用纯静态类来做这件事,就像这样。

class RegisterStaticClass
 {
 public:
 static bool setRegister1( const uint8_t aValue1, const uint8_t aValue2 = 0 );
 static bool setRegister2( const uint8_t aValue1, const uint8_t aValue2 = 0 );
};

我想知道这是否是最好的方法,我认为调用代码现在更容易,因为它必须只做:

 RegisterStaticClass::setRegister1( 23, 45);

这种方法有什么缺点吗?

1 个答案:

答案 0 :(得分:6)

您有效地实现了命名空间。只是使用命名空间将为您提供相同的语法和更好的可读性,您不必担心有人试图创建该类的对象。

在命名空间中创建私有函数或数据成员的方法是使用匿名命名空间:

namespace RegisterStaticClass{
    //public:
    bool setRegister1( const uint8_t aValue1, const uint8_t aValue2 = 0 );
    //private:
    namespace{
        //accessible only within this namespace
        bool setRegister2( const uint8_t aValue1, const uint8_t aValue2 = 0 );
    }
}
//usage:
RegisterStaticClass::setRegister1( 23, 45);
RegisterStaticClass::setRegister2( 23, 45); //error
相关问题