【发布时间】:2017-08-06 23:38:27
【问题描述】:
我希望能够将一个类中的类似函数分组到一个组中,这样我就不需要在每个名称后面加上它的含义。
我看到this question 说你不能在类中拥有命名空间。我还看到this question 建议使用强类型枚举。不过这里的问题是,我不确定这些枚举是否真的可以容纳函数?
问题情境化:
class Semaphore
{
public:
void Set(bool State){Semaphore = State;}
bool Get(){return Semaphore;}
void Wait()
{
while (Semaphore)
{
//Wait until the node becomes available.
}
return;
}
private:
bool Semaphore = 0; //Don't operate on the same target simultaneously.
};
class Node : Semaphore
{
public:
unsigned long IP = 0; //IP should be stored in network order.
bool IsNeighbour = 0; //Single hop.
std::vector<int> OpenPorts;
//Rest of code...
};
目前,NodeClass.Get() 是我获取信号量的方式。然而,这会导致混淆 Get() 实际得到什么。我想要类似于NodeClass.Semaphore::Get() 的东西。否则我必须拥有SemaphoreSet()、SemaphoreGet() 和SemaphoreWait() 之类的函数,这些函数组织得不是很好,也不是很好看。
我曾想过只拥有自己的 Semaphore 类,并在其他类中实例化它,但如果我能坚持继承方法,那就更好了。
所以本质上,是否可以访问像InheritedClass.Group::Function() 这样的继承方法?
【问题讨论】:
-
为什么Node继承自Semaphore?这很重要。
-
@immibis 我需要每个节点都具有信号量功能。但是信号量本身需要操纵。
-
“我需要每个节点都具有信号量功能” - 那么为什么需要 Node 从信号量继承,而不是让信号量作为成员:
Semaphore MySemaphore;? -
我想我能做到,我会考虑的!
标签: c++ class namespaces