正在加载图片...
2.公有派生 在公有派生中,基类的私有成员对派生类来说仍是基类的私有 成员,只能通过基类的公有成员函数访问(相当于可访问性保持 不变),不允许外部函数和派生类的成员函数直接访问。基类中 的公有成员相当于派生类的公有成员,外部函数和派生类的成员 函数可直接访问。 例43 void maino #include <iostream. h> i derived obj lass base ∥定义基类 Int x; obj. setx((10);∥合法 public obj. sety(20);∥合法 void setx (intn)xen; obj. showN;∥合法 void show(0{ cout <<x<< endl;} obj. showy;∥合法 }; lass derived: public base i定义公有派生k C int y public void sety(int n)i y=n; 3 void showy {cout≤<y<end;}2. 公有派生 在公有派生中,基类的私有成员对派生类来说仍是基类的私有 成员,只能通过基类的公有成员函数访问(相当于可访问性保持 不变),不允许外部函数和派生类的成员函数直接访问。基类中 的公有成员相当于派生类的公有成员,外部函数和派生类的成员 函数可直接访问。 例4.3 #include <iostream.h> class base{ //定义基类 int x; public: void setx(int n) { x=n; } void showx() { cout << x << endl; } }; class derived : public base {//定义公有派生类 int y; public: void sety(int n) { y=n; } void showy() { cout << y << endl; } }; void main() { derived obj; obj.setx(10); //合法 obj.sety(20); //合法 obj.showx(); //合法 obj.showy(); //合法 } 7
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有