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

时间:2022-11-24 15:05:02

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

1.父类(DBConnector)

1)DBConnector.h

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>
using namespace std;
class DBConnector
{
private:
 string name;
public:
 DBConnector();
 DBConnector(string _name);
 ~DBConnector();
 
 void show();
};

2)DBConnector.cpp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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

?
1
2
3
4
5
6
7
8
9
#pragma once
#include "DBConnector.h"
class MSSqlConnector :public DBConnector
{
public:
 MSSqlConnector();
 MSSqlConnector(string _name);
 ~MSSqlConnector();
};

2)MSSqlConnector.cpp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "MSSqlConnector.h"
 
MSSqlConnector::MSSqlConnector()
{
}
 
MSSqlConnector::MSSqlConnector(string _name) :DBConnector(_name)
{
  
}
 
MSSqlConnector::~MSSqlConnector()
{
}

3.子类2(MSSqlConnector)

1)MSSqlConnector.h

?
1
2
3
4
5
6
7
8
9
#pragma once
#include "DBConnector.h"
class MSSqlConnector :public DBConnector
{
public:
 MSSqlConnector();
 MSSqlConnector(string _name);
 ~MSSqlConnector();
};

2)MSSqlConnector.pp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "MSSqlConnector.h"
 
MSSqlConnector::MSSqlConnector()
{
}
 
MSSqlConnector::MSSqlConnector(string _name) :DBConnector(_name)
{
  
}
 
MSSqlConnector::~MSSqlConnector()
{
}

4.Test

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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++ 通过指针实现多态实例详解

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