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

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

1.父类(DBConnector)

1)DBConnector.h

#include  
using namespace std; 
class DBConnector 
{ 
private: 
 string name; 
public: 
 DBConnector(); 
 DBConnector(string _name); 
 ~DBConnector(); 
 
 void show(); 
}; 

2)DBConnector.cpp

#include "DBConnector.h" 
#include  
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  
#include  
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++ 通过指针实现多态实例详解_第1张图片

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

你可能感兴趣的:(C++ 通过指针实现多态实例详解)