程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C++ 通過指針實現多態實例詳解

C++ 通過指針實現多態實例詳解

編輯:關於C++

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.運行結果

 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved