从派生作用域调用函数 [英] Calling function from derived scope
本文介绍了从派生作用域调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码似乎与此类似:
I have some code which seems similair to this:
#include <iostream>
class Base {
public:
void test() {
std::cout << "Base::test()" << std::endl;
}
void test2() {
test();
}
};
class Derived : public Base {
public:
void test() {
std::cout << "Derived::test()" << std::endl;
}
};
int main() {
Derived d;
d.test2();
return 0;
}
现在输出ofcourse Base :: test
,但我希望它输出 Derived :: test()
而不使用虚函数调用和使用不同的符号为函数重载调用: Derived :: test
。
Now this outputs ofcourse Base::test()
, however I want it to output Derived::test()
without making use of virtual function calls and using an different notation for the function overload called: Derived::test
.
有人知道这是否可能实现 c>
Does someone know if this is possible to achieve?
推荐答案
template<typename D>
class Base {
public:
void test() {
std::cout << "Base::test()" << std::endl;
}
void test2() {
(static_cast<D*>(this))->test();
}
};
然后,您将从 Derived
code> Base Base
:
Then, you would derive Derived
from Base<Derived>
instead of just Base
:
class Derived : public Base<Derived> {
// ^^^^^^^^^^^^^
// This is the only change required in Derived
public:
void test() {
std::cout << "Derived::test()" << std::endl;
}
};
这是一个 生活示例 。
这篇关于从派生作用域调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文