C++ 通过指针实现多态实例详解

时间:2021-05-20

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.运行结果

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章