C++ 确定哪个子类正在调用父函数

标签 c++ function class exception parent

好的,所以我无法在任何地方找到答案,这是我的第一篇文章,所以请多多关照。 基本上,如果某个子类在特定条件下调用父函数,我需要抛出异常,但另一个子类应该始终能够执行该函数。

--如果您想知道,它是一个具有储蓄和支票子类的帐户类的提款函数。储蓄有最低余额(如果提款导致余额低于最低值则抛出异常)但支票没有最低余额

class parent {
      public:

      int b;
      void A(){
             //1. Throws exception if b < # ONLY when child1 calls
             //2. Always executes code if child2 calls regardless of condition
      }              
}           


class child1 : public parent {
}

class child2 : public parent {
}


int main(){

    child1 one;
    child2 two;

    one.A();        //This needs to throw exception under certain conditions
    two.A();        //This will always execute
}

有人知道如何确定哪个子类正在调用该函数吗?

最佳答案

如果没有循环依赖,就没有简单的方法可以做到这一点。可能最简单的方法是在每个类中重载函数:

class Child1 : public Parent
{
   void A(int v) 
   {
      if (this->b > v)
      {
         throw 1;
      }
      else
      {
         Parent::A(v);
      }
      return;
   }
}

您还可以在基类中将函数设为纯虚函数,以强制所有子级使用自己的拷贝覆盖该函数。

class Parent
{
   virtual void A() =0;
}

class Child1 : public Parent
{
   void A(int v) 
   {
      if (this->b > v)
      {
         throw 1;
      }
      else
      {
         <<do something>>
      }
      return;
   }
}

或者,您可以使用 Functors,但这些会变得非常复杂并且需要 C++11。在这里查看:http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html

关于C++ 确定哪个子类正在调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22820585/

相关文章:

c++ - 定义时 int 总是很短?

c - 返回值的有用性不依赖于所有(仅按值调用)参数

function - 这个Go函数类型 "HandlerFunc"是怎么工作的,来自标准库 "net/http"

javascript - 为什么不应用 CSS 类(使用 JavaScript onload)?

java - 为什么 java 代码没有显示正确的实例数量?

c# - C#方法中的静态参数

c++ - 对由非 T 类型的值初始化的 const T 的引用

c++ - 通过来自另一个翻译单元的指针调用具有内部链接的函数

c++ - 在文本框中显示值-错误

来自变量的 Bash 别名