从派生类调用基方法
例如,我有这样的类:
class Base
{
public: void SomeFunc() { std::cout << "la-la-la\n"; }
};
我从中派生新的类:
class Child : public Base
{
void SomeFunc()
{
// Call somehow code from base class
std::cout << "Hello from child\n";
}
};
我想看看:
la-la-la
Hello from child
我可以从派生类调用方法吗?
I have, for example, such class:
class Base
{
public: void SomeFunc() { std::cout << "la-la-la\n"; }
};
I derive new one from it:
class Child : public Base
{
void SomeFunc()
{
// Call somehow code from base class
std::cout << "Hello from child\n";
}
};
And I want to see:
la-la-la
Hello from child
Can I call method from derived class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当然:
顺便说一句,由于
Base::SomeFunc()
未声明virtual
,Derived::SomeFunc()
隐藏它位于基类中,而不是覆盖它,从长远来看,这肯定会导致一些令人讨厌的意外。因此,您可能希望将声明更改为Thisautomatically made
Derived::SomeFunc()
virtual
,尽管为了清楚起见,您可能更喜欢显式声明它。Sure:
Btw since
Base::SomeFunc()
is not declaredvirtual
,Derived::SomeFunc()
hides it in the base class instead of overriding it, which is surely going to cause some nasty surprises in the long run. So you may want to change your declaration toThis automatically makes
Derived::SomeFunc()
virtual
as well, although you may prefer explicitly declaring it so, for the purpose of clarity.顺便说一句,您可能也想将
Derived::SomeFunc
设为public
。btw you might want to make
Derived::SomeFunc
public
too.您可以通过再次调用带有父类名称前缀的函数来完成此操作。您必须为类名添加前缀,因为可能有多个父级提供名为 SomeFunc 的函数。如果有一个名为 SomeFunc 的自由函数,并且您希望调用它::SomeFunc 就可以完成工作。
You do this by calling the function again prefixed with the parents class name. You have to prefix the class name because there maybe multiple parents that provide a function named SomeFunc. If there were a free function named SomeFunc and you wished to call that instead ::SomeFunc would get the job done.
是的,你可以。请注意,您给方法赋予了相同的名称,但没有将它们限定为虚拟的,编译器也应该注意到这一点。
Yes, you can. Notice that you given methods the same name without qualifying them as
virtual
and compiler should notice it too.