C# · 12月 20, 2021

C++—–对象的继承(一)

#include “stdafx.h”

#include

using namespace std;

//继承:

//减少代码的重复性;

//网页实例:

class news

{

public:

void head()

{

cout << "公共的头部" << endl;

}

void footer()

{

cout << "公共的底部" << endl;

}

void left()

{

cout << "左侧列表" << endl;

}

void content()

{

cout << "新闻播报" << endl;

}

};

class Entertainment

{

public:

void head()

{

cout << "公共的头部" << endl;

}

void footer()

{

cout << "公共的底部" << endl;

}

void left()

{

cout << "左侧列表" << endl;

}

void content()

{

cout << "娱乐" << endl;

}

};

void test01()

{

news m_new;

m_new.head();

m_new.footer();

m_new.left();

m_new.content();

Entertainment m_ent;

m_ent.head();

m_ent.footer();

m_ent.left();

m_ent.content();

}

//避免代码冗余,所以提前抽象一个基类网页;

//重复的代码写到这个基类网页上;

class basePage

{

public:

void head()

{

cout << "公共的头部" << endl;

}

void footer()

{

cout << "公共的底部" << endl;

}

void left()

{

cout << "左侧列表" << endl;

}

};

class news2 : public basePage //继承的写法,表示news2类继承于basePage;

{

public:

void content()

{

cout << "新闻播报" << endl;

}

};

class entertainment2 :public basePage

{

public:

void content()

{

cout << "娱乐" << endl;

}

};

class Game :public basePage

{

public:

void content()

{

cout << "游戏直播" << endl;

}

};

void test02()

{

entertainment2 m_ent2;

news2 m_new2;

Game m_game;

m_ent2.content();

m_new2.content();

m_game.content();

}

int main()

{

test01();

test02();

return 0;

}

//上述的basePage 叫做 基类(父类),其余的 news2,entertainment2 , Game 叫做派生类(子类);