- B类public继承A类,A类里面的private变量,B是不可见的,但是可以通过A类的public函数去访问,切AB两类同时拥有private变量x,B类继承的A类的访问x的函数访问的是A里面的x变量,B类自己的访问private x变量的函数才能去操作B类自己的x变量。测试代码如下:
-
#include<iostream> #include<vector> #include <set> using namespace std; class Mydemo { public: char c; void SetSelf(int x, int y); void ShowSelf(); private: int a; int b; }; class Mydemo2 :public Mydemo { public: void SetSelf2(int x, int y); //void SetSelf(int x, int y); void ShowSelf2(); //void ShowSelf(); int d; private: int a; int b; }; void Mydemo::SetSelf(int x, int y) { a = x; b = y; } void Mydemo::ShowSelf() { cout << "a =" << a << endl << "b =" << b << endl; cout << "c = " << c << endl; } void Mydemo2::SetSelf2(int x, int y) { a = 2*x; b = 2*y; } void Mydemo2::ShowSelf2() { cout << "a =" << a << endl << "b =" << b << endl; } int main() { Mydemo m1; m1.c = 'a'; m1.SetSelf(10, 20); m1.ShowSelf(); Mydemo2 m2; m2.c = 'b'; m2.d = 3; m2.SetSelf(30, 40); m2.ShowSelf(); m2.SetSelf2(30, 40); m2.ShowSelf2(); cout << m2.d << endl; return 0; }
C++学习
最新推荐文章于 2024-09-03 09:15:05 发布