【翁恺】14-子类父类关系

declare an employee class

class Employee {
public:
    Employee(const std::string &name, const std::string &ssn);
    const std::sting &get_name() const;
    void print(std::ostrwam &out) const;
    void pint(std::ostrwam &out,const std::string &msg) const;
protected:
    std::string m_name;
    std::string m_ssn;
}

        &:引用

constructor of employee

Employee::Employee(const sting &name,const string &ssn):m_name(name),m_ssn(ssn){
    //initializer list sets up the values!
}

employee member functions

inline const std::sting & Employee::get_name() const{
    return m_name;
};
inline void Employee::print(std::ostream &out) const{
	out<<m_name<<endl;
	out<<m_ssn<<endl;
};
inline Employee::void pint(std::ostream &out,const std::string &msg) const{
    out<<msg<<endl;
    print(out);
};

 1. print函数重载。2. 尽量使用已有的代码写新的代码,可以避免错误

now add manager

class Manager:public Employee{ // 继承
public:
    Manager(const std::string&name,const std::string ssn,const std::string&title);
    const std::string title_name() const;
    const std::string& get_title() const;
    void print(std::ostream& out) const;
private:
    std::string m_title;
};

创建一个子类的对象,父类的构造函数将会被调用。如果Employee 没有默认构造函数。那么编译会报错。解决:在子类的构造函数中以初始化列表的方式,给父类传递父类构造函数需要的参数。

初始化列表:顺序是按照声明的顺序,而不是在初始化列表中写的顺序。

1. 所有成员变量的初始化

2.父类的初始化。

父类首先被构造,然后是子类被构造。析构时候,先子类后父类。

manager member functions

inline void Manager::print(std::ostream& out) const{
    Employee::print(out);//call the base class print
    out << m_title<<endl;
}
inline const std::string& Manager::get_title() const{
    return m_title;
}
inline const std::string Manager::title_name() const{
    return string(m_title + ":"+m_name);// access base m_naeme
}

 Manager::print 使用了 Employee::print

uses

int main(){
    Employee bob("Bob Jones","555-444-8888");
    Manager bill("Bill Smith","555-444-6666","important person");
    
    string name = bill.get_name();//okay Manager inherits Empoyee
    //string title = bob.get_title();//error
    cout<<bill.title_name()<<"\n"<<endl;
    bill.print(cout);
    bob.print(cout);
    bob.print(cout,"Employee:");
    //bill.print(cout,"Employee:")//error hidden
}

//bill.print(cout,"Employee:")//error

如果父类中存在函数重载,子类中存在一个相同的函数,子类中只有这个函数,父类的被隐藏。只有C++ 如此。原因:C++中,这两个不过是同名而已,并没有关系,把父类的那些函数都隐藏了。

bill.Employee::print(cout,"Employee:")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理心炼丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值