欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

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

来源:本站原创|时间:2020-01-10|栏目: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.运行结果

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

上一篇:C语言 数组中重复的数字分析及方法

栏    目:C语言

下一篇:浅谈c++ 字符类型总结区别wchar_t,char,WCHAR

本文标题:C++ 通过指针实现多态实例详解

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/1679.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有