重构:将友谊委派在子任务中

发布于 2025-01-23 18:20:55 字数 589 浏览 3 评论 0原文

我重构一个代码,其中一堂课有一个朋友函数做很多事情。

class Foo
{
  friend void do_something(Foo& foo);
};

void do_something(Foo& foo)
{
  // More than 2000 lines of ugly code
}

我想在几个小功能中将do_something的内容分开。看起来像这样的东西:

void do_something(Foo& foo)
{
  if(case_1) do_1(foo);
  else if(case_2) do_2(foo);
  else if(case_3) do_3(foo);
  //...
}

是否有一个设计,我可以将友谊转移到子形式do_x(foo&)而不必在班级中声明它们,还是类似的东西以将代码分开?

注意: C ++ 11仅

注意:我不想将子函数写成MacCros

I refactor a code where a class has a friend function doing a lot of stuff.

class Foo
{
  friend void do_something(Foo& foo);
};

void do_something(Foo& foo)
{
  // More than 2000 lines of ugly code
}

I would like to split the content of do_something in several small functions. Something looking like this :

void do_something(Foo& foo)
{
  if(case_1) do_1(foo);
  else if(case_2) do_2(foo);
  else if(case_3) do_3(foo);
  //...
}

Is there a design where I can transfert the friendship to the sub-fuctions do_x(Foo&) without having to declare them in the class, or something similar in order to split the code ?

Note : C++11 only

Note : I don't want to write the sub-functions as maccros

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅气称霸 2025-01-30 18:20:55

我建议您创建一个类似的类dosomehting,而不是让do_something作为函数呼叫其他子函数。

然后,您可以将此类声明为朋友类Dosomehting;的朋友。因此,这些子函数可能是其私人方法。呼叫的方法 - 可以是一种名为void dosomehting :: process(foo& foo)的公共方法:

class Foo
{
  friend class DoSomething;
};

class DoSomething
{
public:
    void process(Foo& foo)
    { 
        if(case_1) do_1(foo);
        else if(case_2) do_2(foo);
        else if(case_3) do_3(foo);
        //...
    }  

private:
    void do_1(Foo& foo);
    void do_2(Foo& foo);
    void do_3(Foo& foo);
};

Instead of having do_something as function calling other sub-functions, I would suggest you to create an analogous class DoSomehting.

Then you could declare this class as a friend with friend class DoSomehting;. So these sub-functions could be its private methods. The method to call -- could be a public method named e.g. like void DoSomehting::process(Foo& foo):

class Foo
{
  friend class DoSomething;
};

class DoSomething
{
public:
    void process(Foo& foo)
    { 
        if(case_1) do_1(foo);
        else if(case_2) do_2(foo);
        else if(case_3) do_3(foo);
        //...
    }  

private:
    void do_1(Foo& foo);
    void do_2(Foo& foo);
    void do_3(Foo& foo);
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文