C++ 通過指針實現多態實例詳解。本站提示廣大學習愛好者:(C++ 通過指針實現多態實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是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.運行結果
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!