There are several syntax errors in this code, so it cannot be compiled. Here is a corrected version:

#include using namespace std;

class Base { public: Base(int m) { n = m++; } virtual void gl() { cout << "Base::gl()..." << n << endl; g4(); cout << "n = " << ++n << endl; g3(); } protected: int n; };

class Derive : public Base { public: void gl() { cout << "Derive::gl()..." << n << endl; a3(); cout << "n = " << ++n << endl; a2(); } private: void a3() { cout << "Derive::a3()..." << endl; } void a2() { cout << "Derive::a2()..." << endl; } };

int main() { Base b(1); Derive d(2); Base* bp = &d; Base& bref = d;

b.gl();
cout << endl;
d.gl();
cout << endl;
bp->gl();
cout << endl;
bref.gl();

return 0;

}

This code defines two classes, Base and Derive, and a main function that creates objects of these classes and calls their gl member functions. The Base class has a constructor that takes an int parameter and initializes the n member variable to the parameter value plus one. It also defines a virtual gl member function that outputs a message and calls two other member functions, g4 and g3, and increments and outputs the n member variable.

The Derive class is derived from Base and overrides the gl member function with its own implementation that outputs a different message and calls two other member functions, a3 and a2, and increments and outputs the n member variable.

In the main function, an object of Base and an object of Derive are created and their gl member functions are called. Then a pointer to the Derive object is assigned to a pointer to Base, and the gl member function is called through the pointer, demonstrating polymorphism. Finally, a reference to the Derive object is assigned to a reference to Base, and the gl member function is called through the reference, again demonstrating polymorphism

#include iostream using namespace std; class BasepublicBaseint m	n=m++; 	virtual void gl coutBaseg1nendl; g4;201 o1 81 at; for o++nendl;g3;voidprotectedint n;class Derive public Basepublicvoid gl!! vo

原文地址: https://www.cveoy.top/t/topic/cxS2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录