Reusing the interface
◆ Inheritance is to take the existing class, clone it, and then make additions and modifications to the clone.
Inheritance
◆ Language implementation technique
◆ Also an important component of the OO design methodology
◆ Allows sharing of design for
— Member data
— Member functions
— Interfaces
◆ Key technology in C++
Interface
◆ The ability to define the behavior or implementation of one class as a superset of another class
Inheritance
#include <iostream> using namespace std; class A { public: A(): i(0) { cout << "A::A()" << endl; } ~A() { cout << "A::~A()" << endl; } void print() { cout << i << endl; } void set(int ii) { i = ii; } private: int i; }; class B :public A { public: void f() { set(20); print(); } }; int main(int argc, const char* argv[]) { B b; b.set(10); b.print(); b.f(); return 0; }运行结果如下,说明类B的对象b生成了,而且其成员函数B::f();成功调用了其继承的类A的函数A::set();和A::print();
如果我们尝试利用类B的对象b直接修改其继承的类A的成员变量i,如下代码所示:
#include <iostream> using namespace std; class A { public: A() : i(0) { cout << "A::A()" << endl; } ~A() { cout << "A::~A()" << endl; } void print() { cout << i << endl; } void set(int ii) { i = ii; } private: int i; }; class B :public A { public: void f() { set(20); i = 30; print(); } }; int main(int argc, const char* argv[]) { B b; b.set(10); b.print(); b.f(); return 0; }那么编译器就会报错,因为成员变量i是private类型,而类B是继承自类A,所以类B的实例化对象b不可直接去访问类A中的成员变量
如果我们将类A中的成员函数修改为protected时,局面就会发生变化:
#include <iostream> using namespace std; class A { public: A() : i(0) { cout << "A::A()" << endl; } ~A() { cout << "A::~A()" << endl; } void print() { cout << i << endl; } protected: void set(int ii) { i = ii; } private: int i; }; class B :public A { public: void f() { set(20); print(); } }; int main(int argc, const char* argv[]) { B b; b.print(); b.f(); return 0; }Scopes and access in C++