您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關C++如何通過指針實現多態,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
C++ 通過指針實現多態實例詳解
1.父類(DBConnector)
1)DBConnector.h
#include <string> using namespace std; class DBConnector { private: string name; public: DBConnector(); DBConnector(string _name); ~DBConnector(); void show(); };
2)DBConnector.cpp
#include "DBConnector.h" #include <iostream> using namespace std; DBConnector::DBConnector() { } DBConnector::DBConnector(string _name) { name = _name; } DBConnector::~DBConnector() { } void DBConnector::show() { cout << name << endl; }
2.子類1(MySqlConnector)
1)MSSqlConnector.h
#pragma once #include "DBConnector.h" class MSSqlConnector :public DBConnector { public: MSSqlConnector(); MSSqlConnector(string _name); ~MSSqlConnector(); };
2)MSSqlConnector.cpp
#include "MSSqlConnector.h" MSSqlConnector::MSSqlConnector() { } MSSqlConnector::MSSqlConnector(string _name) :DBConnector(_name) { } MSSqlConnector::~MSSqlConnector() { }
3.子類2(MSSqlConnector)
1)MSSqlConnector.h
#pragma once #include "DBConnector.h" class MSSqlConnector :public DBConnector { public: MSSqlConnector(); MSSqlConnector(string _name); ~MSSqlConnector(); };
2)MSSqlConnector.pp
#include "MSSqlConnector.h" MSSqlConnector::MSSqlConnector() { } MSSqlConnector::MSSqlConnector(string _name) :DBConnector(_name) { } MSSqlConnector::~MSSqlConnector() { }
4.Test
#include "MySqlConnector.h" #include "MSSqlConnector.h" #include <iostream> #include <string> using namespace std; void main() { MySqlConnector mysql("mysql"); MSSqlConnector mssql("mssql"); DBConnector* p; p = &mysql; p->show(); p = &mssql; p->show(); //mysql.show(); //mssql.show(); }
5.運行結果
關于“C++如何通過指針實現多態”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。