本文共 2416 字,大约阅读时间需要 8 分钟。
继承是面向对象编程中解决代码重复问题的重要机制,它允许我们在保持已有类特性的同时,扩展功能并创建新的派生类。这种层次化的复用体现了面向对象设计的逻辑思维过程。
class Person {public: void SetPerson(const string& name, const string& sex, int age) { name_ = name; sex_ = sex; age_ = age; }private: string name_; string sex_; int age_;};class Student : public Person {public: void SetStudent(const string& name, const string& sex, int age, int stuID) { SetPerson(name, sex, age); stuID_ = stuID; }private: int stuID_;};
访问限定符决定了继承过程中成员的访问级别:
public
:所有继承者可以访问。protected
:子类和派生类可以访问。private
:只有当前类和其派生类可以访问。单独和多继承的实现方式:
// 单继承class student : public person {}// 多继承class A : public B1, public B2 {}
class
的默认继承方式是private
,而struct
默认是public
。template...
子类必须使用public
继承才能访问父类的成员。
子类对象可以被视为基类对象的扩展。
子类覆盖父类成员时,需提前声明:
// 基类class Base {public: void TestFunc() { cout << "Base::TestFunc()" << endl; }private: int b_;};// 派生类class Derived : public Base {public: void TestFunc(int b) { cout << "Derived::TestFunc(int)" << endl; }private: int d_; char b_;};int main() { Derived d; d.TestFunc(10); // 调用派生类函数 d.Base::TestFunc(); // 调用基类函数}
// 基类class Base {public: Base(int b = 10) : b_(b) { cout << "Base::Base(int)" << endl; } Base(const Base& b) : b_(b.b_) { cout << "Base::Base(const Base&)" << endl; } ~Base() { cout << "Base::~Base()" << endl; } Base& operator=(const Base& b) { if (this != &b) { b_ = b.b_; } return *this; }private: int b_;};// 派生类class Derived : public Base {public: Derived(int b = 10, int d = 20) : Base(b), d_(d) { cout << "Derived::Derived(int, int)" << endl; } Derived(const Derived& d) : Base(d), d_(d.d_) { cout << "Derived::Derived(const Derived&)" << endl; } Derived& operator=(const Derived& d) { if (this != &d) { Base::operator=(d); d_ = d.d_; } return *this; } ~Derived() { cout << "Derived::Derived()" << endl; // 调用基类析构 }private: int d_;};
优点:
优点:
在编写代码时,优先考虑组合复用,少用继承。
转载地址:http://biacz.baihongyu.com/