如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
how to access protected member of super class to its derived class. if a function already declared in the derived class with same name?
在以下情况下,我想访问超级类的受保护成员。 如果有人有任何想法,请告诉我如何实现这一目标? 此受保护函数调用来自同一类的受保护函数。
#include<iostream>
#include<String.h>
using namespace std;
/*Derived Class*/
class SuperParentClass
{
protected:
void protected_funtion()
{
cout << "I'm a protected function of SuperParentClass..." << endl;
}
};
class ParentClass : public SuperParentClass
{
public:
void public_function(void)
{
cout << "I'm a public function of ParentClass..." << endl;
protected_funtion();
}
protected:
void protected_funtion()
{
cout << "I'm a protected function of ParentClass..." << endl;
}
};
int main()
{
ParentClass objParentClass;
objParentClass.public_function();
return 0;
}
实际结果:
I'm a public function of Parent Class...
I'm a protected function of Parent Class...
预期成果:
I'm a public function of Parent Class...
I'm a protected function of Super Parent Class...`
您可以使用:
void public_function(void)
{
cout << "I'm a public function of ParentClass..." << endl;
SuperParentClass::protected_funtion();
}
活在神霹雳上
派生类中的函数与基类中的函数同名会隐藏基类中的函数。
因此,您需要使用限定名来访问基类中的隐藏函数。
例如,相对于您的代码,您可以编写例如
void public_function(void)
{
cout << "I'm a public function of ParentClass..." << endl;
protected_funtion();
SuperParentClass::protected_funtion();
}
如果具有相同名称的函数的类型不同(否则可能会出现歧义(,则可以在派生类中使用 using 声明来引入基类中函数的声明。例如
#include <iostream>
struct A
{
void f() const
{
std::cout << "A::f()n";
}
};
struct B : A
{
using A::f;
void f()
{
std::cout << "B::f()n";
}
void test()
{
f();
const_cast<const B *>( this )->f();
}
};
int main()
{
B().test();
return 0;
}
程序输出为
B::f()
A::f()
在这里,如果没有类 B 中的 using 声明,则父类 A 中声明的函数 f 将被派生类 B 中具有相同名称的函数声明隐藏。
using 声明允许在派生类 B 的作用域中使在类 A 中声明的函数 f 可见。
相关文章:
- 具有多个类、派生类的C++正向声明
- 是否可以使用 using 将基类中的公共成员重新声明为派生类中的私有成员?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- 将派生类的构造函数声明为父类的友元
- 从模板基类派生是否在派生类声明的点实例化模板
- 从基类的唯一指针中声明派生类的类型
- C++ 多态性:如果派生类中的虚函数在基类中声明了常量,是否需要将其声明为常量
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- 如何声明从 QApplication 派生的 Qt 类并覆盖通知函数?
- 是否可以在引用另一个派生类的派生类中声明复制构造函数?
- 冲突的声明(外部基础与派生)
- 声明派生类的对象而不指定它
- 通过派生类模板参数指定基类模板参数之一。如何使用基类的 using 声明
- 声明嵌套基模板类实例是派生类的好友
- 是否可以在C++中声明基类,以便只能通过创建函数创建从它派生的类
- 在基类主体内声明但通过派生类召集的函数
- 如何在基本模板类中声明成员,其中类型取决于派生类的类型
- 在派生的C 类中,访问基类受保护成员作为公共的访问声明
- 在基类中使用派生类,而在基类之后声明派生类
- 在派生类或基类中,我应该在哪里声明友元类