众所周知,继承是面向对象编程的一项特性,它允许我们从一个基类创建派生类。派生类继承基类的特性。
假设我们在基类和派生类中都定义了相同的函数。现在,当我们使用派生类对象调用该函数时,将执行派生类的函数。
在这里,派生类中的成员函数隐藏了基类中的成员函数。这被称为隐藏基类成员函数。
示例 1:C++ 隐藏基类成员函数
// C++ program to demonstrate shadowing base class member function
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
输出
Derived Function
在这里,Base 和 Derived 类中都定义了相同的 print() 函数。
因此,当我们使用派生类对象 derived1 调用 print() 时,将执行 Derived 中的 print(),从而隐藏了 Base 中的函数。
正如我们所见,函数被隐藏是因为我们是从 Derived 类的对象调用该函数的。
如果我们从 Base 类的对象调用 print() 函数,则该函数不会被隐藏。
// Call function of Base class
Base base1;
base1.print(); // Output: Base Function
在 C++ 中访问被隐藏的函数
要访问基类中被隐藏的函数,我们使用作用域解析运算符 ::。
我们还可以通过使用基类指针指向派生类对象,然后通过该指针调用函数来访问被隐藏的函数。
示例 2:C++ 从基类访问被隐藏的函数
// C++ program to access shadowed function
// in main() using the scope resolution operator ::
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1, derived2;
derived1.print();
// access print() function of the Base class
derived2.Base::print();
return 0;
}
输出
Derived Function Base Function
在这里,语句
derived2.Base::print();
访问了 Base 类的 print() 函数。
示例 3:C++ 在派生类中调用被隐藏的函数
// C++ program to call the shadowed function
// from a member function of the derived class
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
// call overridden function
Base::print();
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
输出
Derived Function Base Function
在这个程序中,我们在 Derived 类内部调用了基类成员函数。
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
Base::print();
}
};
请注意代码 Base::print();,它在 Derived 类内部调用了 Base 类的成员函数 print()。
示例 4:C++ 使用指针调用被隐藏的函数
// C++ program to access shadowed function using pointer
// of Base type that points to an object of Derived class
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
// pointer of Base type that points to derived1
Base* ptr = &derived1;
// call function of Base class using ptr
ptr->print();
return 0;
}
输出
Base Function
在这个程序中,我们创建了一个 Base 类型的指针 ptr。该指针指向 Derived 对象 derived1。
// pointer of Base type that points to derived1
Base* ptr = &derived1;
当我们使用 ptr 调用 print() 函数时,它会调用 Base 中的成员函数。
// call function of Base class using ptr
ptr->print();
这是因为尽管 ptr 指向一个 Derived 对象,但它实际上是 Base 类型。因此,它会调用 Base 的成员函数。
为了重写 Base 函数而不是访问它,我们需要在 Base 类中使用虚函数。