派生类的知识点

1、派生一个类没有多余的内存开销,所需的内存就是储存成员的内存。

2、派生类一般将基类部分的数据放在前面:

#define debug qDebug()<<
class A
{
public:
    int a;
};

class B : public A
{
public:
    int b;
};

int main(int argc, char *argv[])
{
    B bb;
    bb.a = 666;
    bb.b = 888;
    debug &bb <<endl<<&bb.a <<&bb.b;
}

所以基类的指针(指针的值即地址值)可以指向派生类的地址,因为根本就是同一个地址值。

3、基类的指针和引用可以指向派生类对象:

    A & r = bb;
    A * p = &bb;

4、派生类可以访问基类的保护和公有类型的成员,不能访问私有成员。(最方便的方法是基类中只有公有成员)

5、可以通过引用/指针调用基类中的函数:

class A
{
public:
    int a;
    void debugValue(int i)
    {
        debug "A"<<i;
    }
    void debugValue(bool b)
    {
        debug "A"<<b;
    }
};

class B : public A
{
public:
    int b;
    void debugValue(QString str)
    {
        debug "B"<<str;
    }
    void debugValue(int i)
    {
        debug "B"<<i;
    }
};

int main(int argc, char *argv[])
{
    B b;
    b.debugValue("hello");
    b.debugValue(666);
    A & r = b;
    r.debugValue(55);
    r.debugValue(false);
}

7、在派生类中用::可以便捷访问基类中的成员:

#define debug qDebug()<<
class A
{
public:
    int a = 999;
    void debugValue()
    {
        debug "hello";
    }
};

class B : public A
{
public:
    int b = 888;
    void debugValue()
    {
        A::a = 444;
        debug A::a;
        A::debugValue();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值