关于C++的隐藏 (hidden),重载(overload),重写(override)小结。

关于隐藏 (hidden)
假如继承以后,子类出现父类同名函数, 即使参数的形式不同, 也会导致父类的函数隐藏, 不参与函数匹配,不能使用。
这个链接讲的不错。https://zhuanlan.zhihu.com/p/575423511

#include <iostream>
using namespace std;
class Vehicle {
    
    
public:
    void accelerate() {
    
     cout << "Increasing speed: "; }
};
class Aeroplane : public Vehicle {
    
    
    public:
    void accelerate(int height) {
    
    
        cout << "Accelerating at a height of: " << height;
    }
};

int main() {
    
    
	Aeroplane plane;
	plane.accelerate(1000);
	plane.accelerate();  //这里出错!main.cpp:17:25: error: no matching function for call to ‘Aeroplane::accelerate()’
	cout << endl;
}

如果子类的instance就是想调用父类的同名不同参的函数呢?方法有两个。

  1. 显式调用父类版本的函数
    b.A::func(); // 显式指定父类版本,合法
    #include
    using namespace std;
    class Vehicle {
    public:
    void accelerate() { cout << "Increasing speed: "; }
    };
    class Aeroplane : public Vehicle {
    public:
    void accelerate(int height) {
    cout << "Accelerating at a height of: " << height;
    }
    };

int main() {
Aeroplane plane;
plane.accelerate(1000);
plane.Vehicle::accelerate();
cout << endl;
}

  1. 用using
    using A::func; // 解开父类重载函数的默认隐藏。
#include <iostream>
using namespace std;
class Vehicle {
    
    
public:
    void accelerate() {
    
     cout << "Increasing speed: "; }
};
class Aeroplane : public Vehicle {
    
    
    public:
    using Vehicle::accelerate;
    void accelerate(int height) {
    
    
        cout << "Accelerating at a height of: " << height;
    }
};

int main() {
    
    
	Aeroplane plane;
	plane.accelerate(1000);
	plane.accelerate();
	cout << endl;
}
  1. 当然也可以直接在子类的函数里面调用
class Aeroplane : public Vehicle {
    
    
    public:
    void accelerate(int height) {
    
    
        Vehicle::accelerate();  
        cout << "Accelerating at a height of: " << height;
        
    }
};

关于overload

关于override
如果不用virtual,怎么实现多态呢?可以用cast。但是对不同子类的object都要cast到对应的子类类型,显然很不方便。
static_cast<Circle *>(s)->draw();

#include <iostream>
#include <vector>

using namespace std;

class Shape {
    
    
public:
	void draw() {
    
     cout << "Drawing a generic shape...\n"; }
};

class Circle: public Shape {
    
    
public:
	void draw() {
    
     cout << "Drawing a circle...\n"; }
};

int main() {
    
    
	vector<Shape *> shapes;      // Vector of pointers to Shape instances

	// Create a pointer to a child class of Shape and append it to the vector 
	shapes.push_back(new Circle);

	for (auto s: shapes)
		static_cast<Circle *>(s)->draw();      

	for (auto s : shapes)       // Release allocated memory
		delete s;
}

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/132785314