好的,所以我无法在任何地方找到答案,这是我的第一篇文章,所以请多多关照。 基本上,如果某个子类在特定条件下调用父函数,我需要抛出异常,但另一个子类应该始终能够执行该函数。
--如果您想知道,它是一个具有储蓄和支票子类的帐户类的提款函数。储蓄有最低余额(如果提款导致余额低于最低值则抛出异常)但支票没有最低余额
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/