c++子类调用父类的同名函数

 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 #include <memory>
 5 #include <map>
 6 #include <hash_map>
 7 #include <conio.h>
 8 
 9 template <typename T> class c1;
10 template <typename T> class c2;
11 
12 template <typename T>
13 class c1 {
14 public:
15     void operator[](size_t i) {
16         std::cout << "c1" << std::endl;
17      }
18 };
19 
20 template <typename T>
21 class c2 : public c1<T> {
22 public:
23     //类里声明赋值的话,是在构造函数没有赋值时的默认值
24     int        mInt_1 = 1;
25     const int &mInt_2 = 2;
26     const int  mInt_3 = 3;
27 
28 public:
29     //会覆盖掉声明的赋值
30     //如果引用和const在声明和构造函数里都没有赋值的话,肯定会报错的
31     c2(const int _1 = 4, const int _2 = 5, const int _3 = 6) : mInt_1(_1), mInt_2(_2), mInt_3(_3) { }
32 public:
33     void operator[](size_t i) {
34         std::cout << mInt_1 << std::endl;
35         std::cout << mInt_2 << std::endl;
36         std::cout << mInt_3 << std::endl;
37     }
38     //调用的是父类的[]重载函数
39     void printFunc() { (*(c1<T> *)this)[10]; }
40 };
41 
42 int main(void)  {
43     c2<int> tempC2;
44     tempC2.printFunc();
45 
46     std::cout << "enter any keyboard to exit." << std::endl;
47     _getch();
48     return 0;
49 }
1 //若用虚函数来修饰[]重载,则无论如何子类也无法调用到父类的函数
2 virtual void operator[](const size_t i) { }
3 
4 //调用的是子类的[]重载
5 *(dynamic_cast<c1<T> *>(this))[10];

另外,注意子类父类的虚函数的返回和参数都要一样,dynamic_cast只有在对有虚函数的类强转时才能用

猜你喜欢

转载自www.cnblogs.com/AIKaGa/p/12901910.html