如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?

how to access protected member of super class to its derived class. if a function already declared in the derived class with same name?

本文关键字:派生 声明 函数 如果 受保护 超类 成员 访问      更新时间:2023-10-16

在以下情况下,我想访问超级类的受保护成员。 如果有人有任何想法,请告诉我如何实现这一目标? 此受保护函数调用来自同一类的受保护函数。

#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 可见。