当前位置:主页 > 软件编程 > C代码 >

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

时间:2021-03-31 09:14:54 | 栏目: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.运行结果

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

您可能感兴趣的文章:

相关文章