目录
一、继承中同名成员的处理
- 如果子类和父类拥有同名成员
- 优先调用子类的成员 可以通过作用域调用父类成员
- 同名的成员函数 子类会隐藏掉父类所以的版本 也可以加作用域进行调用
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class Base
{
public:
Base()
{
this->m_A = 100;
}
int m_A;
void func()
{
cout << "Base中的func调用" << endl;
}
void func(int a)
{
cout << "Base中的func(int a)调用" << endl;
}
};
class Son :public Base
{
public:
Son()
{
this->m_A = 200;
}
int m_A;
void func()
{
cout << "Son中的func调用" << endl;
}
};
void test01()
{
Son s;
cout << s.m_A << endl;
cout << "Base中的m_A:" << s.Base::m_A << endl;
s.func();
s.Base::func();
//同名的成员函数 子类会隐藏掉父类所以的版本
//s.func(10); 只是隐藏 不是覆盖 用下述方法调用
s.Base::func(10);
}
int main()
{
test01();
return 0;
}
二、继承中的同名静态成员处理
- 如果子类和父类拥有同名成员
- 优先调用子类的成员 可以通过作用域调用父类成员
- 同名的成员函数 子类会隐藏掉父类所以的版本 可以用作用域调用
- 访问方式有两种
- 另一种通过类名进行访问
- 一种通过对象进行访问
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class Base
{
public:
static int m_A;//共享数据,编译阶段分配内存,类内声明,类外初始化
static void func()
{
cout << "base中的func调用" << endl;
}
static void func(int a)
{
cout << "base中的func(int a)调用" << endl;
}
};
int Base::m_A = 10;
class Son :public Base
{
public:
static int m_A;
static void func()
{
cout << "son中的func调用" << endl;
}
};
int Son::m_A = 100;
void test01()
{
//对m_A进行访问
Son s;
cout << "Son中的m_A=" << s.m_A << endl;
cout << "Base中的m_A=" <<s.Base::m_A << endl;
//通过类名进行访问
cout << "通过类名进行访问,Son中的m_A=" << Son::m_A << endl;
cout << "通过类名进行访问,Base中的m_A=" << Son::Base::m_A << endl;
//同名成员函数进行调用
s.func();
Son::func();
//子类中同名函数 会隐藏父类中所有同名成员函数的重载版本,可以通过类名访问到父类中的其他版本
s.Base::func(1);
Son::Base::func(1);
}
int main()
{
test01();
system("pause");
return 0;
}
三、多继承语法
- Class 子类:继承方式 父类1,继承方式 父类2
- 当两个父类 有同名的成员 被子类继承后,调用时要加作用域区分
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class Base1
{
public:
Base1()
{
this->m_A = 10;
}
int m_A;
};
class Base2
{
public:
Base2()
{
this->m_B = 10;
}
int m_B;
};
class Son :public Base1, public Base2
{
public:
int m_C;
int m_D;
};
void test01()
{
cout << sizeof(Son) << endl;
Son s;
cout << "Base1的m_A=" << s.m_A << endl;
cout << "Base2的m_B=" << s.m_B << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
四、菱形继承的问题及解决
解决方案:利用虚继承virtual Animal类属于虚基类