【发布时间】:2020-01-03 04:16:29
【问题描述】:
我希望继承类B 重载其基类A 的成员函数func()。我知道当被B 的对象访问时,B::func() 将被调用,A::func() 将被隐藏,除非通过A:: 或using 明确引用。
现在假设A 有另一个方法another_func(),它调用func()。假设所有成员和继承都是public,当然B会继承another_func()。
现在,如果我从B::another_func() 调用func(),我希望调用B::func(),但是当我尝试它时,调用A::func()。对于给定的代码结构,有没有办法实现我正在寻找的行为?
我找到了this,但并不完全相同。
here 的回答总体上很有帮助,但并不能真正解决我的问题。
如果措辞令人困惑,这里是代码形式:
标题:
#include <iostream>
class A
{
public:
void func() { std::cout << "Called A::func()" << std::endl; };
void another_func() { func(); };
};
class B: public A
{
public:
void func() { std::cout << "Called B::func()" << std::endl; };
};
来源:
int main(int argc, char** argv)
{
B B_obj;
B_obj.func();
B_obj.another_func(); // I want this to call B::func?
return 0;
}
这段代码的输出是:
Called B::func()
Called A::func()
我想要的输出是:
Called B::func()
Called B::func()
显而易见的答案是直接做B::func()而不是B::another_func(),但我的实际情况更复杂,如果能做类似上面的事情,对我来说非常有用。
编辑
基于this,我尝试将A::func 设为virtual 方法,它按我想要的方式工作。但是,我也读到过调用虚函数的成本要高得多。有没有更好的办法?
【问题讨论】:
-
尝试在另一个函数中添加“this”?
-
你的意思是把
another_func()的定义改成this->func();吗?我试过了,它产生了同样不受欢迎的结果。 -
嗯,你有没有尝试在 B 类中覆盖该函数?
标签: c++ class c++11 inheritance overloading