#include<iostream>
using namespace std;
class ClassA
{
public:
int x;
void PublicShow();
ClassA(int x = 1, int y = 2, int z = 3);
~ClassA();
protected:
int y;
void ProtectedShow();
private:
int z;
void PrivateShow();
};
class ClassB:public ClassA
{
public:
int a;
void PublicShow();
ClassB(int a = 3, int b = 4, int c = 5, int x = 1, int y = 2, int z = 3);
~ClassB();
protected:
int b;
void ProtectedShow();
private:
int c;
void PrivateShow();
};
int main()
{/*
ClassA number(1, 2, 3);
number.x = 1;// public属性 外部可以访问
number.PublicShow();// public方法 外部可以访问
number.y = 2;//(X) protected属性 外部无法访问
number.ProtectedShow();//(X) protected方法 外部无法访问
number.z = 3;//(X) private属性 外部无法访问
number.PrivateShow();//(X) private方法 外部无法访问
*/
ClassB number(4, 5, 6, 1, 2, 3);
number.PublicShow();
number.PublicShow();
return 0;
}
/***************************AAAAAAAAAAAAA******************************/
ClassA::ClassA(int x, int y, int z)
{
this->x = x;
this->y = y;
this->z = z;
}
ClassA::~ClassA()
{
}
void ClassA::PublicShow()
{
cout << x << "+" << y << "+" << z << endl;
//Public中方法,x y z都能访问
}
void ClassA::ProtectedShow()
{
cout << x << "+" << y << "+" << z << endl;
//Protected中方法,x y z都能访问
}
void ClassA::PrivateShow()
{
cout << x << "+" << y << "+" << z << endl;
//Private中方法,x y z都能访问
}
/***************************BBBBBBBBBBBBBBBBBBB*************************/
ClassB::ClassB(int a, int b, int c,int x,int y,int z):ClassA(x, y, z)
{
this->a = a;
this->b = b;
this->c = c;
}
ClassB::~ClassB()
{
}
void ClassB::PublicShow()
{
cout << x << "+" << y << "+" << a << "+" << b << "+" << c << endl;
//cout << x << "+" << y << "+" << z << endl;
//ClassB Public方法中,z无法访问
}
void ClassB::ProtectedShow()
{
cout << x << "+" << y << "+" << a << "+" << b << "+" << c << endl;
//cout << x << "+" << y << "+" << z << endl;
//ClassB Protected方法中,z无法访问
}
void ClassB::PrivateShow()
{
cout << x << "+" << y << "+" << a << "+" << b << "+" << c << endl;
//cout << x << "+" << y << "+" << z << endl;
//ClassB Private方法中,z无法访问
}
/*总结
* 1.z是A的隐私部属性(private),ClassB采用public继承了ClassA,但是只能访问public和protected
* 2.如果子类和父类方法相同,优先调用子类自己的方法,PublicShow()
*/
Public继承
最新推荐文章于 2024-05-29 10:35:18 发布