C++派生类与基类的关系
派生类与基类有这些关系:
1.公有派生类从基类继承所有成员和成员函数
2.公有派生类无法直接访问从基类继承的私有成员,但可以通过继承的公共接口访问。
3.公有派生类无法继承基类的友元函数。
4.基类先于派生类被创建,派生类先于基类被析构。
5.派生类的构造函数使用初始化列表来初始化它的成员。两种方式:使用基类的默认构造函数;显式调用基类的构造函数。如果初始化列表什么都不写,则默认使用前者。
类声明:
//Class.h -- Declaration of class #ifndef _CLASS_H_ #define _CLASS_H_ #include <string> using std::string; class Player { public: enum career{WARRIOR,WIZARD,ASSASSIN}; enum sex{MALE,FEMALE,UNKNOWN}; private: string player_name; sex player_sex; unsigned int player_level; career player_career; public: Player(const string pn = "none",sex ps = MALE,unsigned int pl = 1,career pc = WARRIOR); ~Player(); string get_career(); sex get_sex(){return player_sex;}; string get_name(){return player_name;}; friend void welcome(const Player & pr); }; //Derived from class Player class RankedPlayer:Player { private: unsigned int ranking; public: RankedPlayer(const string pn = "none",sex ps = MALE,unsigned int pl = 1,career pc = WARRIOR,unsigned int r = 999); unsigned int get_rank(){return ranking;}; void show_rank(); }; #endif // _CLASS_H_
类定义:
//ClassDefine.cpp -- Definition of class #include "Class.h" #include <iostream> //Methods for class Player Player::Player(const string pn,sex ps,unsigned int pl,career pc):player_name(pn),player_sex(ps),player_level(pl),player_career(pc) { std::cout<<"New player joined in.\n"; } Player::~Player() { std::cout<<"Player "<<get_name()<<" has quited.\n"; } string Player::get_career() { string c; switch(player_career) { case WARRIOR:{c = "warrior";break;} case WIZARD:{c = "wizard";break;} case ASSASSIN:{c = "assassin";break;} default:{break;} } return c; } void welcome(const Player & pr) { if(pr.player_sex == Player::MALE) { std::cout<<"Welcome "<<pr.player_name<<", his career is "<<pr.player_career<<".\n"; } else if(pr.player_sex == Player::FEMALE) { std::cout<<"Welcome "<<pr.player_name<<", her career is "<<pr.player_career<<".\n"; } else { std::cout<<"Welcome "<<pr.player_name<<".\n"; } } //Methods for class RankedPlayer RankedPlayer::RankedPlayer(const string pn,sex ps,unsigned int pl,career pc,unsigned int r):Player(pn,ps,pl,pc) { ranking = r; } void RankedPlayer::show_rank() { std::cout<<get_name()<<"("<<get_career()<<")"<<"'s ranking is: "<<ranking<<"\n"; }
类使用:
//Use Class #include "Class.h" int main(void) { Player p1; welcome(p1); Player p2("Joseph",Player::UNKNOWN,99); welcome(p2); RankedPlayer p3("Jotaro",Player::MALE,99,Player::WIZARD,1); //welcome(p3); p3.show_rank(); return 0; }