亲宝软件园·资讯

展开

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

人气:0
想了解C++ 通过指针实现多态实例详解的相关内容吗,在本文为您仔细讲解C++ 多态的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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.运行结果

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

加载全部内容

相关教程
猜你喜欢
用户评论