使用派生类的对象访问基类的方法,该对象具有相同的方法 [英] Accessing base class's method with derived class's object which has a method of same name
本文介绍了使用派生类的对象访问基类的方法,该对象具有相同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用派生类的对象访问base的foo()时。
when accessing foo() of "base" using derived class's object.
#include <iostream>
class base
{
public:
void foo()
{
std::cout<<"\nHello from foo\n";
}
};
class derived : public base
{
public:
void foo(int k)
{
std::cout<<"\nHello from foo with value = "<<k<<"\n";
}
};
int main()
{
derived d;
d.foo();//error:no matching for derived::foo()
d.foo(10);
}
如何访问具有同名方法的基类方法在派生类中。
生成的错误已显示。
如果我不清楚我会道歉,但我觉得我已经把自己弄清楚了。
提前感谢。
how to access base class method having a method of same name in derived class. the error generated has been shown. i apologize if i am not clear but i feel i have made myself clear as water. thanks in advance.
推荐答案
您可以使用base :: foo $添加 c $ c>到派生类:
You could add using base::foo
to your derived class:
class derived : public base
{
public:
using base::foo;
void foo(int k)
{
std::cout<<"\nHello from foo with value = "<<k<<"\n";
}
};
编辑 这个问题解释了为什么你的 base :: foo()
不能直接使用派生的
而不使用使用
声明。
The answer for this question explains why your base::foo()
isn't directly usable from derived
without the using
declaration.
这篇关于使用派生类的对象访问基类的方法,该对象具有相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文