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:")