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