c ++, inheritance

C ++  Inheritance is the relationship between class and class, is a very simple and very intuitive concept, the real world is similar to inherit, such as the son inherited his father's property.

Inheritance (Inheri Tan CE) may be understood as a class member variables and member functions acquired from another class procedure. For example, class B inherits from class A, then B will have A member variables and member functions.

In C ++, a derived ( Derive ) and Inheritance is a concept, but a different angle stations. Inheritance is the industry receives his father's son, the father derived the industrial heritage to his son.

Inherited class is called the parent class or a base class inherit the class is called a derived class, or subclass. "Subclass" and "parent" usually placed together called "base class" and "derived class" call usually placed together.

In addition to members of the derived class has a base class, you can also define your own new members to enhance the functionality class.

The following are two typical scenarios using inheritance:
1) When you create a new class with existing classes similar, but more of when a number of member variables or member functions, you can use inheritance, this will not only reduce the amount of code, and the new class will have all the features of the base class.

2) When you need to create multiple classes, they have many similarities when member variables or member functions, you can use inheritance. Common members of these classes can be extracted, is defined as the base class, and inherited from the base class, the code can be saved, but also facilitate subsequent modifications members.

Here we define a base class People, and thereby derive Student class:

 

 

#include<iostream>
using namespace std;
//基类 Pelple
class People{
public:
void setname(char *name);
void setage(int age);
char *getname();
int getage();
private:
char *m_name;
int m_age;
};
void People::setname(char *name){ m_name = name; }
void People::setage(int age){ m_age = age; }
char* People::getname(){ return m_name; }
int People::getage(){ return m_age;}
//派生类 Student
class Student: public People{
public:
void setscore(float score);
float getscore();
private:
float m_score;
};
void Student::setscore(float score){ m_score = score; }
float Student::getscore(){ return m_score; }
int main(){
Student stu;
stu.setname("小明");
stu.setage(16);
stu.setscore(95.5f);
cout<<stu.getname()<<"的年龄是 "<<stu.getage()<<",成绩是 "<<stu.getscore()<<endl;
return 0;
}

Guess you like

Origin www.cnblogs.com/qianrushi1/p/11564365.html