private继承方式:
(1)
#include <QtCore/QCoreApplication>
#include <QDebug>
class A
{
public:
A(){}
A(const QString a,const QString b,const QString c):
pubAttr(a),
priAttr(b),
proAttr(c)
{}
QString pubAttr;
void show()
{
qDebug() << pubAttr <<" "<< priAttr << " "<<proAttr;
}
private:
QString priAttr;
void print()
{
qDebug() << pubAttr <<" "<< priAttr << " "<<proAttr;
}
protected:
QString proAttr;
void dis()
{
qDebug() << pubAttr <<" "<< priAttr << " "<<proAttr;
}
};
//私有继承---------------------
class B : private A
{
public:
B(){}
B(QString a,QString b,QString c,QString d,QString e,QString f):
A(a,b,c),
pubBttr(d),
priBttr(e),
proBttr(f)
{
}
//输出基类A中的公共成员以及保护成员
void showAttr()
{
qDebug()<< pubAttr << proAttr /*<< priAttr */; //(基类中的私有成员不可见)
A::show(); //基类的公共成员对于子类是可见的
dis(); //基类的受保护成员对于子类是可见的
//print(); //基类的私有成员对于子类是不可见的
}
void show()
{
qDebug() << pubBttr <<" "<< priBttr << " "<<proBttr;
}
QString pubBttr;
private:
QString priBttr;
protected:
QString proBttr;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//-----------------------------私有继承
//---------------子类对于基类属性的访问控制
//构建B对象
B bttr("Hello","Class","World","pub","pri","pro");
//调用B中的方法
qDebug() <<"-------------------";
bttr.showAttr();
qDebug() <<"-------------------";
//基类的私有继承:子类的对象对基类成员都不可见(子类对象不可调用基类的任何成员)
//不能通过B的对象调用A的任何方法
//bttr.A::show(); //基类的公共成员对于子类的对象是不可见的
//bttr.A::print(); //基类的私有成员对于子类的对象是不可见的
//bttr.A::dis(); //基类的保护成员对于子类的对象也是不可见的
return a.exec();
}