【问题标题】:Namespace Functions within Class alternatives?类替代方案中的命名空间函数?
【发布时间】: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


【解决方案1】:

如果你真的想这样做,你可以通过deleteing 子类中的成员函数来强制用户使用基类名称调用:

class Base {
  public:
    void Set(bool) { }
};

class Derived : public Base {
  public:
    void Set(bool) = delete;
};

int main() {
    Derived d;
    // d.Set(true); // compiler error
    d.Base::Set(true);
}

但是,如果在子类上调用 Set 的语义与在基类上调用 Set 时所期望的语义明显不同,则您可能应该使用数据成员并命名成员函数正如你所描述的那样:

class Base {
  public:
    void Set(bool) { }
};

class Derived {
  public:
    void SetBase(bool b) {
        b_.Set(b);
    }
  private:
    Base b_;
};

int main() {
    Derived d;
    d.SetBase(true);
}

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2010-10-26
    • 2011-03-29
    相关资源
    最近更新 更多