基类:基类是面向对象编程语言中的一个类,从该类派生出其他类。继承基类的类具有基类的所有成员,也可以具有一些附加属性。基类成员和成员函数继承到派生类的Object。基类也称为父类或超类。
派生类:从现有类创建的类。派生类继承基类的所有成员和成员函数。派生类相对于 Base 类可以具有更多功能,并且可以轻松访问 Base 类。派生类也称为子类或子类。
创建派生类的语法:
class BaseClass{
// members....
// member function
}
class DerivedClass : public BaseClass{
// members....
// member function
}
基类和派生类的区别:
S.No. | BASE CLASS | DERIVED CLASS |
---|---|---|
1. |
A class from which properties are inherited. | A class from which is inherited from the base class. |
2. |
It is also known as parent class or superclass. | It is also known as child class subclass. |
3. |
It cannot inherit properties and methods of Derived Class. | It can inherit properties and methods of Base Class. |
4. |
Syntax: Class base_classname{ … }. | Syntax: Class derived_classname : access_mode base_class_name { … }. |
下面是说明Base Class和Derived Class 的程序:
CPP
// C++ program to illustrate
// Base & Derived Class
#include
using namespace std;
// Declare Base Class
class Base {
public:
int a;
};
// Declare Derived Class
class Derived : public Base {
public:
int b;
};
// Driver Code
int main()
{
// Initialise a Derived class geeks
Derived geeks;
// Assign value to Derived class variable
geeks.b = 3;
// Assign value to Base class variable
// via derived class
geeks.a = 4;
cout << "Value from derived class: "
<< geeks.b << endl;
cout << "Value from base class: "
<< geeks.a << endl;
return 0;
}
输出:
Value from derived class: 3
Value from base class: 4
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。