c++面向对象: public 继承, 虚方法, 动态绑定


title: ‘c++面向对象: public 继承, 虚方法, 动态绑定’
date: 2018-11-04 13:00:34
tags:

  • oop
  • public inheritance
  • virtual methods
  • dynamic binding
    categories: cpp
    blog: https://withas.me

学了java中的面向对象后再来学习c++的面向对象, 对两者设计理念上的差异有不少的体会: c++更多地考虑了程序的运行效率(默认静态绑定, 没有垃圾回收等), 把很多繁琐的操作留给了使用者; 而java是贯彻了面向对象的思维, 有一种彻头彻尾的面向对象的感觉, 而把一些背后的机制向使用者隐藏了. 这篇blog主要记录c++中public继承相关的内容.

Public Inheritance

c++中有public, protected, private三种继承方式, 其中public是最常用的.

public继承描述的是一种is-a的关系, derived-class是base-class的一个子集且一般是真子集. 比如从Student类可以派生出Cadre类, Cadre一定是Student, 而Student不一定是Cadre. 这种关系是单向的, 不具有对称性.

class Student {
private:
   int id;
   string name;
public:
   int getId() const { return id; }

   void setId(int id) { Student::id = id; }

   const string &getName() const { return name; }

   void setName(const string &name) { Student::name = name; }
};

class Cadre : public Student {
private:
   string duty;
public:
   const string &getDuty() const { return duty; }

   void setDuty(const string &duty) { Cadre::duty = duty; }
};

Cadre由Student派生, 则Cadre直接继承了Student的所有public成员. Private成员也成为了derived-class的一部分, 但是只能通过base-class的public和protected方法访问. 例如Cadre从Student那里继承了name, 但是不能直接访问, 只能通过Student::getName访问.

class Cadre : public Student {
	...
public:
    ...
    void showInfo() const {
        cout << Student::getName() << endl;
        cout << Student::getId() << endl;
        cout << duty << endl;
    }
};

Constructos and Destructos

class Student {
private:
    int id;
    string name;
public:
    Student(int id, const string &name) : id(id), name(name) {}
    ...
};

class Cadre : public Student {
private:
    string duty;
public:
    Cadre(int id, const string &name, const string &duty) : Student(id, name), duty(duty) {}
	...
};

Derived-class不能直接直接访问继承自base-class的private成员, 所以不能在constructors里直接对它们初始化, 必须借助base-class的constructors. 并且base-class必须先于derived-class被构造. 如果要使用base-class的constructor有参数则必须在derived-class的constructor中以初始化参数列表的方式调用, 如上例. 如果不在derived-class的constructor中显式地调用base-class的constructor, 则默认使用base-class的不带参数的constructor(不存在则编译会产生错误).

Base-class会先于derived-class被构造. 析构的方向恰与之相反, derived-class的destructor先于base-class被执行.

Is-a

前面提到过public继承是一种is-a的关系, 所以base-class的指针可以指向derived-class的对象, base-class的引用可以引用derived-class的对象.

    Student *pc = new Cadre(1, "J", "monitor");
    Student &rc = *pc;

但是通过base-class的指针和引用只能使用base-class存在的属性, 如:

	rc.getId();//ok
    rc.getDuty();//error

Virtual Methods

Redefine

有时候为了让derived-class有不同的功能我们可能需要重写base-class的方法.

class Student {
private:
    int id;
    string name;
public:
    void showInfo() const {
        cout << name << endl;
        cout << id << endl;
    }

};

class Cadre : public Student {
private:
    string duty;
public:
    void showInfo() const {
        cout << Student::getName() << endl;
        cout << Student::getId() << endl;
        cout << duty << endl;
    }
};

这样我们对Student对象和Cadre的对象分别调用showInfo的时候就会输出不同的结果.

但是这样会产生一个问题:

    Cadre *pc = new Cadre(1, "J", "monitor");
    Student &rc = *pc;
    pc->showInfo();
    cout << endl;
    rc.showInfo();
/*output:
J
1
monitor

J
1*/

同一个Cadre对象, 用它自己的指针调用和用Student的引用调用时结果不一样. 查看输出结果可以知道用Student的引用调用的时候运行的是Student::showInfo, 而非在Cadre中重写的方法.

Virtual methods

为了让base-class引用的derived-class可以调用derived-class重写的方法, 我们可以使用virtual.

class Student {
public:
    ...
    virtual void showInfo() const {
        cout << name << "\t" << id;
    }
};

class Cadre : public Student {
public:
	...
    virtual void showInfo() const {
        Student::showInfo();//reusing code 
        cout << "\t" << duty;
    }
};

再来看看输出结果:

	Cadre *pc = new Cadre(1, "J", "monitor");
    Student &rc = *pc;//Student reference
    pc->showInfo();
    cout << endl;
    rc.showInfo();//invoke Cadre::showInfo() instead of Student::showInfo()
/*output:
J       1       monitor
J       1       monitor
*/

如果不使用virtual, 调用的方法取决于引用或者指针的类型; 使用, 则由引用或者指向的对象本身决定, 也就是说可以使用base-class的引用或者指针调用在derived-class的重写的方法.

当base-class中的方法被标记为virtual时, derived-class中重写的方法也被自动标记为virtual. 不过一般为了方便阅读, 也将derived-class中重写的方法标记为virtual.

对于base-class中在derived-class被重写的方法一般都会被标记为virtual. 另外有derived-class的base-class的destructors最好被标记为virtual.

class A {
private:
    string *a;
public:
    A() { a = new string("Hello"); }

    ~A() { delete a; }
};

class B : public A {
private:
    string *b;
public:
    B() : A() { b = new string("world"); }

    ~B() { delete b; }
};

int main() {
    A *pb = new B();
    delete pb;
}

delete pb时会直接调用A::~A(), B中b的内存没有成功被释放. 所以为了内存的正确释放最好把base-class的destructor标记为virtual.

Static and Dynamic Binding

绑定是指调用哪个具体的方法. 例如上面不加virtual关键词时rc.showInfo会调用引用类型的showInfo, 即Student::showInfo; 而加上virtual会调用Cadre::showInfo.

	Cadre *pc = new Cadre(1, "J", "monitor");
    Student &rc = *pc;//Student reference
    rc.showInfo();

static binding是指在编译的时候就决定了调用的方法, 而dynamic binding是在程序运行过程中才能决定(因为对于一个base-class的指针可能指向base-class也可能指向derived-class). 这种dynamic binding的特性被称为多态.

c++默认的绑定方式是static binding. 对于dynamic binding对象内部会增加一个virtual function table (vtbl), 它负责记录这个对象应该调用的方法. 尽管dynamic binding看上去有更多的好处, 然而c++默认的绑定方式是static binding, 这样程序的运行效率更高. 与之对比, java中没有virtual function, 它默认的就是动态绑定.

dynamic binding产生的多态有什么好处呢? 看下面这个例子:

class Class {
private:
    vector<Student *> students;
public:
    void addStudent(Student *student) {
        students.push_back(student);
    }

    void listStudent() {
        for (auto &s: students) {
            s->showInfo();
            cout << endl;
        }
    }
};
//
Class cla;
Student a = Student(1, "Y");
Cadre b = Cadre(2, "Z", "monitor");
Student c = Student(3, "W");
cla.addStudent(&a);
cla.addStudent(&b);
cla.addStudent(&c);
cla.listStudent();
/*output
Y	1
Z	2	monitor
W	3
*/

在Class中我们全都储存的是Student的指针, 在打印Student List的时候就可以根据指向的具体对象输出相应的信息.

Code

完整演示代码:

#include <iostream>
#include <vector>

using namespace std;

class Student {
private:
    int id;
    string name;
public:
    Student(int id, const string &name) : id(id), name(name) {}

    int getId() const { return id; }

    void setId(int id) { Student::id = id; }

    const string &getName() const { return name; }

    void setName(const string &name) { Student::name = name; }

    virtual void showInfo() const {
        cout << name << "\t" << id;
    }

    virtual ~Student() {}
};

class Cadre : public Student {
private:
    string duty;
public:
    Cadre(int id, const string &name, const string &duty) : duty(duty), Student(id, name) {}

    const string &getDuty() const { return duty; }

    void setDuty(const string &duty) { Cadre::duty = duty; }

    virtual void showInfo() const {
        Student::showInfo();
        cout << "\t" << duty;
    }

};

class Class {
private:
    vector<Student *> students;
public:
    void addStudent(Student *student) {
        students.push_back(student);
    }

    void listStudent() {
        for (auto &s: students) {
            s->showInfo();
            cout << endl;
        }
    }
};

int main() {
    Cadre *pc = new Cadre(1, "J", "monitor");
    Student &rc = *pc;
    pc->showInfo();
    cout << endl;
    rc.showInfo();
    delete pc;
    cout << endl;
    Class cla;
    Student a = Student(1, "Y");
    Cadre b = Cadre(2, "Z", "monitor");
    Student c = Student(3, "W");
    cla.addStudent(&a);
    cla.addStudent(&b);
    cla.addStudent(&c);
    cla.listStudent();
    return 0;
}

懒惰的我终于又开始更新了.

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值