C++ 运行基类函数,然后运行继承的类函数
可能重复:C++ 运行基类函数,然后运行继承的类函数,c++,oop,C++,Oop,可能重复: 编辑人员完全没有抓住要点:我想说的是,如果有很多类继承Base,我不想为每个类都调用Base::myFunction() 我真的不知道该如何表达这个问题,但我希望从代码中可以明显看出(这可能不是真正编译的,我写得很快): 类基 { 布尔标志=假; void myFunction() { flag=true; //在这里运行继承类的myFunction() } }; A类:公共基地 { void myFunction() { //做一些聪明的事情,而不必在这里设置旗帜。 } };
编辑人员完全没有抓住要点:我想说的是,如果有很多类继承Base,我不想为每个类都调用
Base::myFunction()
强>
我真的不知道该如何表达这个问题,但我希望从代码中可以明显看出(这可能不是真正编译的,我写得很快):
类基
{
布尔标志=假;
void myFunction()
{
flag=true;
//在这里运行继承类的myFunction()
}
};
A类:公共基地
{
void myFunction()
{
//做一些聪明的事情,而不必在这里设置旗帜。
}
};
int main()
{
我的班级;
myClass.myFunction();//设置标志,然后运行聪明的东西
std::coutA类:公共基地
{
void myFunction()
{
Base::myFunction();//首先-如果要使用指针,请使用虚拟函数。
然后,您只需要在派生类实现中调用基类myFunction。
见示例:
class Base
{
bool flag = false;
virtual void myFunction ()
{
flag = true;
}
};
class A : public Base
{
virtual void myFunction ()
{
Base::myFunction(); // call base class implementation first
// do some clever stuff without having to set the flags here.
}
};
int main ()
{
A myClass;
myClass.myFunction(); // set the flags and then run the clever stuff
std::cout << myClass.flag << endl; // should print true
return 0;
}
由于您的继承结构,派生类中的myFunction()调用排除了基类中版本的调用,因此标志永远不会设置为“true”。您使用空实现创建另一个函数(将在子类中重写),并在myFunction
中调用该函数。类似这样:
class Base
{
bool flag = false;
void myFunction ()
{
flag = true;
// here run the inherited class's myFunction()
myDerivedFunction();
}
virtual void myDerivedFunction()
{
// this should be implemented by subclasses.
}
};
class A : public Base
{
void myDerivedFunction ()
{
// do some clever stuff without having to set the flags here.
}
};
我想说的是,如果很多类继承Base,我不想调用Base::myFunction()
每一个都是如此!@Ben然后让你的动作成为构造函数的一部分。这是真正从基类自动调用某些东西的唯一方法。@chrisaycock-不可能实现我想要的……谢谢。@Ben:那么你恐怕就不走运了。考虑一下:5年后,有人编写了一个新的base
子类。你会怎么做Base::myFunction()
知道要运行什么代码吗?@suszterpatt:有意义。谢谢。你的意思是虚拟作废myFunction
?请参阅解释我已经知道这个方法,并想避免它……但这是最接近的答案,所以我会接受它。+1要强制子类实现你可以使用myDerivedFunction()
纯虚拟。
class Base
{
bool flag = false;
virtual void myFunction ()
{
flag = true;
}
};
class A : public Base
{
virtual void myFunction ()
{
Base::myFunction(); // call base class implementation first
// do some clever stuff without having to set the flags here.
}
};
int main ()
{
A myClass;
myClass.myFunction(); // set the flags and then run the clever stuff
std::cout << myClass.flag << endl; // should print true
return 0;
}
class Base
{
bool flag = false;
virtual void cleverCalc() = 0;
virtual void myFunction ()
{
flag = true;
cleverCalc();
}
};
class A : public Base
{
virtual void cleverCalc()
{
// do some clever stuff without having to set the flags here.
}
};
class Base
{
bool flag = false;
void myFunction ()
{
flag = true;
// here run the inherited class's myFunction()
myDerivedFunction();
}
virtual void myDerivedFunction()
{
// this should be implemented by subclasses.
}
};
class A : public Base
{
void myDerivedFunction ()
{
// do some clever stuff without having to set the flags here.
}
};