21xrx.com
2025-04-28 05:28:02 Monday
文章检索 我的文章 写文章
C++实验五:派生与继承-单基派生
2023-07-02 17:50:08 深夜i     13     0
C++ 实验 派生 继承 单基派生

本次C++实验五中,我们将学习派生与继承中的单基派生。在C++中,类可以使用派生和继承实现代码重用和扩展。单基派生是一种继承关系,其中派生类继承于单个基类,并且可以从基类中继承成员。

派生类通过继承基类中的公共和保护成员来访问这些成员,但不能访问基类的私有成员。派生类也可以添加自己的成员,从而扩展基类。

下面是一个简单的例子来说明单基派生:

#include <iostream>
#include <string>
using namespace std;
// Base class
class Person
{
  protected:
    string name;
  public:
    void setName(string s)
    
      name = s;
    
};
// Derived class
class Student : public Person
{
  public:
    void display()
    
      cout << "Name: " << name << endl;
    
};
int main()
{
  Student s;
  s.setName("Alice");
  s.display();
  return 0;
}

在上面的例子中,我们定义了一个名为“Person”的基类,其中包括一个受保护的成员变量“name”和一个公共成员函数“setName”,用于为名称设置值。然后,我们定义了一个名为“Student”的派生类,该类公开了一个名为“display”的公共成员函数,用于显示名称。该类还从“Person”类中继承了“name”成员,因此我们可以在“display”函数中直接访问它。

在主函数中,我们创建了一个学生对象,设置了其名称,然后调用了“display”函数以显示该名称。

本次实验中,我们还可以学习到受保护权限。受保护成员和私有成员相似,但受保护成员可以在派生类中访问。例如:

#include <iostream>
#include <string>
using namespace std;
// Base class
class Person
{
  protected:
    string name;
  public:
    void setName(string s)
    
      name = s;
    
};
// Derived class
class Student : public Person
{
  public:
    void displayName()
    
      cout << "Name: " << name << endl;
    
};
// Another derived class
class Teacher : public Person
{
  public:
    void displayName()
    
      cout << "Teacher name: " << name << endl;
    
};
int main()
{
  Student s;
  Teacher t;
  // The following line will show error because name is protected
  // s.name = "Bob";
  s.setName("Alice");
  s.displayName();
  t.setName("Smith");
  t.displayName();
  return 0;
}

在上面的例子中,我们定义了一个名为“Teacher”的子类,该类重写了“displayName”函数以添加“Teacher name:”前缀。然后在主函数中,我们分别创建一个名为“Student”的学生对象和一个名为“Teacher”的教师对象,并分别为它们设置名称。在这种情况下,“name”成员是保护的,因此我们不能直接访问它。在子类中,我们可以通过公共函数“setName”来设置“name”,然后通过受保护成员“name”来显示它。

总之,单基派生是C++中实现代码重用和扩展的一种方法。派生类可以从基类中继承成员,并可以添加自己的成员来扩展基类。此外,在单基继承中,派生类可以通过公共和受保护成员来访问基类中的成员。

  
  

评论区

    相似文章