最近部门主管要对我们这批实习生进行一次C++的考试。要考核组合,继承与虚函数的知识。所以自己就抽空一段代码,加深对组合与继承的理解。我对组合和继承的理解是:
一个类A由类B组成,或者说类A包含类B,前者就获得后者的接口,可以用后者的接口来实现自己的功能;而类A继承类B,类A可获得类B的接口,即类B的接口都属于类A所有。而组合关系类A只有使用类B接口的权限。
而虚函数是继承的范畴,组合没有虚函数一说。成员函数一旦被声明为虚函数,子类可重写父类的虚函数。并且可以用父类的指针或引用指向子类的对象,来调用子类的虚函数。当成员函数被声明为纯虚函数时,该类称为抽象类,不能被实例化,一般被用来做类模板,需要声明子类来重写其功能。
下面附上代码:
//class.cpp
#ifndef CLASS_H
#define CLASS_H
#include <iostream>
#include <string>
using namespace std;
//公司类,主要是公司名称
class Com
{
private:
string company_name;
public:
Com() { company_name = "xx"; }
void print() { cout << company_name; }
};
//员工类,也是基类
class Worker
{
public:
//名字参数需要声明const,才可把字符串作为参数传入
Worker(int id, const string& na, const string& pos) : id_num(id), name(na), position(pos){}
int get_id() const { return id_num; }
string& get_name() { return name; }
string& get_pos() { return position; }
//纯虚函数,不可定义,留给子类复写
virtual void print() = 0;
//包含公司类,一个员工应该有具体的公司,声明为保护,子类可直接调用
protected:
Com com;
private:
//三个基本信息:身份证,名字,职位
int id_num;
string name;
string position;
};
//财务部类,继承于工人
class Finance : public Worker
{
public:
Finance(int id, const string& na, const string& pos, int amt):Worker(id, na, pos), amount(amt){}
int get_amt() const { return amount; }
void print();
//当前金额
private:
int amount;
};
//研发部类,继承于工人
class Research : public Worker
{
public:
Research(int id, const string& na, const string& pos, int pro) :Worker(id, na, pos), pro_num(pro) {}
int get_pro() const { return pro_num; }
void print();
//当前项目数
private:
int pro_num;
};
//财务人员的信息
void Finance::print()
{
//包含对象的接口
com.print();
cout << "My id num is " << get_id() << "My name is " << get_name()
<< "My pos is " << get_pos() << "The current amount is " << get_amt() << endl;
}
//研发人员的信息
void Research::print()
{
//包含对象的接口
com.print();
cout << "My id num is " << get_id() << "My name is " << get_name()
<< "My pos is " << get_pos() << "The current project num is " << get_pro() << endl;
}
#endif // !CLASS_H
测试代码:
//class.h
#include "class.h"
int main()
{
//声明一个基类的指针
Worker* prt;
Finance finance(112, "Marry", "finance", 1000);
Research research(456, "Jack", "research", 5);
//调用的是Finance::print()
finance.print();
//调用的是Research::print()
research.print();
//基类指针指向Finance对象,调用的是Finance::print()
prt = &finance;
prt->print();
//基类指针指向Research对象,调用的是Research::print()
prt = &research;
prt->print();
system("pause");
return 0;
}*/