简体   繁体   English

如何为不同的类重用相同的实现方法

[英]How to reuse the same implementation method for diferent classes

I'm practicing c++ and I got stuck on the following codes trying to optimize them. 我正在练习c ++,但我仍然坚持使用以下代码来尝试优化它们。 I'd like to know if there is something I can do to optimize their method's implementation. 我想知道我是否可以采取一些措施来优化方法的实现。 Because the methods are the same except for the consts. 因为除了consts之外的方法是相同的。 Thanks in advance. 提前致谢。

dominios.h dominios.h

class HP {
private:

  int valor;

  static const int LIMITE_INFERIOR = 0;
  static const int LIMITE_SUPERIOR = 1000;

public:

  void setValor(int);
  int getValor() {
    return valor;
  }
};

class MP {
private:

  int valor;

  static const int LIMITE_INFERIOR = 0;
  static const int LIMITE_SUPERIOR = 500;

public:

  void setValor(int);
  int getValor() {
    return valor;
  }
};

dominios.cpp dominios.cpp

void HP::setValor(int valor) {

  if (valor < LIMITE_INFERIOR) this->valor = LIMITE_INFERIOR;
  else if (valor > LIMITE_SUPERIOR) this->valor = LIMITE_SUPERIOR;
  else this->valor = valor;
}

void MP::setValor(int valor) {

  if (valor < LIMITE_INFERIOR) this->valor = LIMITE_INFERIOR;
  else if (valor > LIMITE_SUPERIOR) this->valor = LIMITE_SUPERIOR;
  else this->valor = valor;
}

As you can see the setValor of both classes are the same. 正如您所看到的,两个类的setValor是相同的。 I tried to do hierarchy using a "template" but that didn't work for me because of the consts. 我尝试使用“模板”进行层次结构,但由于这些结果,这对我不起作用。

this->valor = std::clamp(valor, LIMITE_INFERIOR, LIMITE_SUPERIOR);

template <typename Tag, int lo, int hi>
class Metric {
private:
  int valor;

public:
  void setValor(int v) { valor = std::clamp(v, lo, hi); }
  int getValor() { return valor; }
};

struct HPTag;
using HP = Metric<HPTag, 0, 1000>;

struct MPTag;
using MP = Metric<MPTag, 0, 500>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将成员函数用于同一类的不同对象 - How to use a member function for diferent objects of same class 有几个C ++类需要使用相同的静态方法和不同的实现 - Several C++ classes need to use the same static method with a different implementation 仅在某些子类中重写相同的方法,如何避免重复? - Overriding same method in only some child classes, how to avoid duplication? 如何处理具有相同方法的不同类? - How to deal with different classes which have the same method? 如何在从抽象基派生的类中实现相同的方法? - How to implement the same method in classes derived from an abstract base? 如何让某些派生类使用相同的方法,而另一些派生类使用另一个方法? - How to let some derived classes use the same method, and some other derived classes use another? 对多个类重用运算符&lt;&lt; - Reuse an operator<< for several classes 如何覆盖纯虚拟方法,但仍强制子类实现相同的方法? - How can I override a purely virtual method, yet still force child classes to implement the same method? 如何减少大量包装类的实现代码? - How to reduce the implementation code of lots of wrapper classes? DLL和EXE中具有相同名称和父类但实现不同的类中的问题 - problem in classes with same name and parent in DLL and EXE but with different implementation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM