When the base class and the derived class have functions with the same name, No matter the number of parameters is the same or different , the subclass object will always directly call the function of the same name of the derived class. If you want to call the function of the same name of the base class , you need to use a base class pointer or reference. If you now want to use the same calling form, you can call the function implementation version of the derived class or the implementation version of the base class, you need to use the virtual function
However, the teacher said that only the function prototypes can be declared as Virtual function, so how to implement the above function for functions with the same name that have different number or types of formal parameters?
欧阳克2017-06-10 09:50:57
You can define it like this and then redefine it as needed in subclasses:
class Base {
public:
virtual void print(int) = 0;
virtual void print(float) = 0;
};
The root of this problem lies in how C++ finds the function. It must know the name and parameters of the function, so you must clearly define both. The return value can be vague. For example, the copy function in a subclass can return a subclass.