请参看以下法典:
#include <iostream>
using namespace std;
class Base {
public:
virtual void Message() = 0;
};
class Intermediate : public Base {
};
class Final : public Intermediate {
void Message() {
cout << "Hello World!" << endl;
}
};
int main() {
Final final;
/* Wont work (obviously):
Final* finalPtr = &final;
finalPtr->Message();
*/
// Works:
Intermediate* finalPtr = &final; // or Base* finalPtr = &final;
finalPtr->Message();
return 0;
}
Take note of the following:
- In the abstract Base class, the pure virtual function message() is public
- Intermediate class (also abstract) inherits from Base class (Does message() function remain public pure virtual in Intermediate?)
- Final class inherits from Intermediate class and message() function is private (by default)
- In main, an object of type Final is created
- An Intermediate pointer to the Final object is created
Question: If you run the program, the line finalPtr->Message(); successfully invokes Final s implementation of message() function though its private. How does that happen? Does a base class override or ignore a derived class access restrictions?
Related Question: In relation to (2.) above, what is the right way to define Intermediate class? Does one need to re-declare the pure virtual function message() from the base class bearing in mind that Intermediate class is not intended to provide an implementation.
<>光> 对《守则》进行了数字火星孔径仪和微软视像素演化器(cl)的测试,并在两种情况下都做了公正的罚款。