实现两种几乎相似的方法

时间:2021-04-07 14:18:07

标签: c++

我需要用两个相似的方法来实现一个类,它们是重载的:

class MyClass {        
  public:              
    int myMethod(int a) {  
      // Logic here
    }
    int myMethod(int b, int c) {  
      // Logic here
    }
};

我想重用代码并且两者的代码非常相似,我正在考虑创建一些通用方法并在实现中在它们之间进行选择。

class MyClass {        
  public:    
    int myMethod(int a) {  
      myGenericMethod(a, 0, 0);
    }
    int myMethod(int b, int c) {  
      myGenericMethod(0, b, c);
    }
  private:
    int myGenericMethod(int a, int b, int c) {
      // Full logic is here
    }   
};

但我仍然想知道这个解决方案是否可行。也许有更优雅的解决方案?

0 个答案:

没有答案