C++子父类中重名变量

C++子父类中变量重名可能比较少遇见,但是如果真的遇见了是怎样一种规则呢?

下面代码举例说明

#include "stdafx.h"
#include<iostream>
using namespace std;


class Father
{
public:
    Father(){ age = 50; };
    int age;
    int getAge() const {
        printf("getAge of Father %d \r\n",age);
        return age; }
    void setAge(int val) { age = val; }
protected:
private:
};

class Son :public Father
{
public:
    Son(){ age = 30; };
    int age;
    int getAge() const {
        printf("getAge of Son %d\r\n",age);
        return age; }
    void setAge(int val) { age = val; }
protected:
private:
};


int _tmain(int argc, _TCHAR* argv[])
{
    auto pFu = (Father*)(new Son());

    auto pZi = new Son();

    printf("age of Father is %d \r\n", pFu->age);

    printf("age of Son is %d \r\n", pZi->age);

    pFu->getAge();

    pZi->getAge();

    while (true)
    {

    }

    return 0;
}

打印结果:

// age of Father is 50

// age of Son is 30

// getAge of Father 50

// getAge of Son 30

通过这个打印结果说明,如果是子类实例化,那么 父类指针指向父类成员,以及函数。子类指针指向子类成员,以及函数。意思就是看左边是什么类型的指针就行了。

如果成员函数是虚函数 ,例如 上面的父类中,getAge改为虚函数。

class Father
{
public:
    Father(){ age = 50; };
    int age;
    virtual int getAge() const {
        printf("getAge of Father %d \r\n",age);
        return age; }
    void setAge(int val) { age = val; }
protected:
private:
};

程序打印结果:

// age of Father is 50

// age of Son is 30

// getAge of Son 30

// getAge of Son 30

总结就是 ,如果是虚函数,那么成员变量还是看左边指针类型,函数是看子类函数,并且子类函数是调用子类自身的变量

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值