C++ 派生类隐藏基类同名方法
我正在读一篇文章,上面写着 这将调用派生的::f(complex)。为什么?好吧,记住这一点 派生的不声明“使用Base:f;”,因此很明显Base::f(int) 不能调用和Base::f(double) 我决定尝试一下,并使用这个代码C++ 派生类隐藏基类同名方法,c++,c++11,C++,C++11,我正在读一篇文章,上面写着 这将调用派生的::f(complex)。为什么?好吧,记住这一点 派生的不声明“使用Base:f;”,因此很明显Base::f(int) 不能调用和Base::f(double) 我决定尝试一下,并使用这个代码 class Base { public: virtual void f( int ) { cout << "Base::f(int)" << endl; } virtual
class Base {
public:
virtual void f( int ) {
cout << "Base::f(int)" << endl;
}
virtual void f( double ) {
cout << "Base::f(double)" << endl;
}
virtual void g( int i = 10 ) {
cout << i << endl;
}
};
class Derived: public Base {
using Base::f;
public:
void f( complex<double> ) {
cout << "Derived::f(complex)" << endl;
}
void g( int i = 20 ) {
cout << "Derived::g() " << i << endl;
}
};
int main() {
Derived d;
d.f(1.0);
}
我的问题是如何使用Base::f代码>以及如何解决此问题?简单。您应该在类的public部分下编写“using”声明,如下所示。若将声明放在private部分,则派生类可以使用基函数,但它们将成为派生类的私有成员。这就是编译器抛出“不可访问”错误的原因
#include <iostream>
#include <complex>
using namespace std;
class Base {
public:
virtual void f( int ) {
cout << "Base::f(int)" << endl;
}
virtual void f( double ) {
cout << "Base::f(double)" << endl;
}
virtual void g( int i = 10 ) {
cout << i << endl;
}
};
class Derived: public Base {
public:
using Base::f;
void f( complex<double> ) {
cout << "Derived::f(complex)" << endl;
}
void g( int i = 20 ) {
cout << "Derived::g() " << i << endl;
}
};
int main() {
Derived d;
d.f(1.0);
}
#包括
#包括
使用名称空间std;
阶级基础{
公众:
虚空f(int){
是否可以将使用Base::f;
放在派生类的公共部分下?
#include <iostream>
#include <complex>
using namespace std;
class Base {
public:
virtual void f( int ) {
cout << "Base::f(int)" << endl;
}
virtual void f( double ) {
cout << "Base::f(double)" << endl;
}
virtual void g( int i = 10 ) {
cout << i << endl;
}
};
class Derived: public Base {
public:
using Base::f;
void f( complex<double> ) {
cout << "Derived::f(complex)" << endl;
}
void g( int i = 20 ) {
cout << "Derived::g() " << i << endl;
}
};
int main() {
Derived d;
d.f(1.0);
}