公共继承例子
#include<iostream>
using namespace std;
//公共继承
class Base {
public:
int m_A;
protected: //保护和私有的属性和行为(函数)只能类内访问
int m_B;
private:
int m_C;
};
class Son1:public Base{
};
void test01() {
Son1 s1;
s1.m_A = 100; //可访问 public权限
cout<<s1.m_A<<endl;
}
int main() {
test01();
system("pause");
return 0;
}
输出结果:
例子
#include<iostream>
using namespace std;
class Base {
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son1 :public Base {
public:
void func() {
m_A = 10; //父类中的公共权限成员 到子类中依然是公共权限
m_B = 10; //父类中的保护权限成员 到子类中依然是保护权限
//m_C = 10; //父类中的私有权限成员 子类访问不到
}
};
void test01() {
Son1 s1;
s1.m_A = 100;
//s1.m_B = 100; //到Son1中 m_B是保护权限 类外访问不到
}
int main() {
system("pause");
return 0;
}
保护继承例子
#include <iostream>
using namespace std;
class Base {
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
//保护继承,使得父类中的可访问成员全变成保护权限
class Son2 :protected Base {
public:
void fun() {
m_A = 100; //父类中公共成员,到子类中变为保护权限
m_B = 100; //父类中保护成员,到子类中变为保护权限
//m_C = 100; //父类中私有成员 子类访问不到
}
};
void test02() {
Son2 s2;
//s1.m_A = 1000; //在Son2中 m_A变为保护权限 ,因此类外访问不到
//s1.m_B = 1000; //在Son2中 m_B保护权限 不可以访问
}
int main() {
system("pause");
return 0;
}
例子
#include <iostream>
using namespace std;
// 基类
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
输出结果
Total area: 35