[英]c++ calling static function from virtual function
I have virtual method that calls static method of appropriate class: 我有调用适当类的静态方法的虚方法:
class A{
public:
static void bar() {std::cout<<"bar A\n";}
virtual void foo(){
//Some A work...
bar();
}
};
class B : public A{
public:
static void bar() {std::cout<<"bar B\n";}
virtual void foo() override {
//Some B work...
bar(); //prints bar B, as intended.
}
};
But now I want to have class C, with method foo(), with the only difference of calling C::bar() in the end: 但是现在我想拥有类C,使用方法foo(), 最后调用C :: bar() 的唯一区别是:
class C : public A {
public:
static void bar() override {std::cout<<"bar C\n";}
virtual void foo(){
//Some **A** work...
bar(); //I want to print "bar C" here
}
}
However, here I needed to make full copy of method A::foo definition. 但是,这里我需要制作方法A :: foo定义的完整副本。 I could also introduce dummy virtual method like `virtual void callStaticBar(){bar();} and override it in class C with the same text.
我还可以引入虚拟虚方法,如`virtual void callStaticBar(){bar();},并在类C中用相同的文本覆盖它。 Is there more elegant way to do such a thing?
是否有更优雅的方式来做这样的事情?
No. If C::foo()
is not defined, calling foo()
on a C
instance will really call A::foo()
; 不。如果没有定义
C::foo()
,在C
实例上调用foo()
将真正调用A::foo()
; since class A
has no knowing of class C
(except is those cases with the vtable), there is no way for A::foo()
to call C::bar()
, regardless of the fact that the original call came from a C
instance. 因为
A
类不知道C
类(除了那些带有vtable的情况), A::foo()
无法调用C::bar()
,无论原始调用来自a C
实例。
You need to use your method of dummy virtual method or to tell us more about what you want to achieve, as they might be a better solution in a particular situation. 您需要使用虚拟虚拟方法的方法或告诉我们更多关于您想要实现的内容,因为它们在特定情况下可能是更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.