c++中存在三种继承方式 注意:任何继承都不可访问父类的私有权限(private)修饰的成员变量
虽然继承不可访问私有(private)成员变量 但是在利用 sizeof(子类对象) 运算时是包含父类的私有(private)成员变量的,只是访问不到。
公共继承 继承的所有变量保留原来的访问权限
保护继承 继承的所有变量的访问权限为 protected
私有继承 继承的所有变量的访问权限为 private
#include <iostream>
using namespace std;
class Base
{
public:
int m_Pub;
protected:
int m_Pro;
private:
int m_Pri;
};
class Son : public Base //public 继承的所有变量保留原来的访问权限
{
public:
void see()
{
m_Pub = 10;
m_Pro = 20;
//m_Pri = 30; 报错 访问不到父类私有权限变量
}
};
class Son1 :protected Base //protected 继承的所有变量的访问权限为 protected
{
public:
void see()
{
m_Pub = 10;
m_Pro = 20;
}
};
class Son2 :private Base //private 继承的所有变量的访问权限为 private
{
public:
void see()
{
m_Pub = 10;
m_Pro = 20;
}
};
void testSon()
{
Son ss;
ss.m_Pub = 20;
//ss.m_Pro = 5; 访问不到
Son1 ss1;
//ss1.m_Pub = 20; 访问不到
//ss1.m_Pro = 5; 访问不到
}
没啥好说的
1.父类构造
2.子类构造
3.子类析构
4.父类析构
默认调用自己的成员变量以及方法
想要调用父类的需要加作用域
一旦子类有与父类同名的函数 父类的重载方法必须利用作用域调用
静态修饰同上 只是多了一个类名调用
#include <iostream>
using namespace std;
class Father
{
public:
Father()
{
cout << "Father 的构造函数" << endl;
}
~Father()
{
cout << "Father 的析构函数" << endl;
}
int m_A = 20;
static int s_A;
void see()
{
cout << "Father 的see()函数" << endl;
}
void see(int a)
{
cout << "Father 的see(int a)函数" << endl;
}
static void staSee()
{
cout << "Father 的静态 staSee()函数" << endl;
}
static void staSee(int a)
{
cout << "Father 的静态 staSee(int a)函数" << endl;
}
};
int Father::s_A = 20;
class Son : public Father
{
public:
Son()
{
cout << "Son 的构造函数" << endl;
}
~Son()
{
cout << "Son 的析构函数" << endl;
}
int m_A = 10;
static int s_A;
void see()
{
cout << "Son 的see()函数" << endl;
}
static void staSee()
{
cout << "Son 的静态 staSee()函数" << endl;
}
};
int Son::s_A = 20;
void test()
{
Son s;
cout << s.m_A << endl; //默认调用子类的成员变量
cout << s.Father::m_A << endl; //加作用域调用父类的成员变量
s.see();
s.Father::see();
s.Father::see(6);
cout << s.s_A << endl;//子类静态成员变量通过对象访问方式
cout << s.Father::s_A<< endl; //父类静态成员变量通过对象访问方式
cout << Son::Father::s_A << endl;//父类静态成员变量通过类名访问方式
s.staSee();//子类静态方法调用
s.Father::staSee();//父类对象静态方法调用
s.Father::staSee(6);//父类对象重载静态方法调用
Son::Father::staSee();//父类类名静态方法调用
Son::Father::staSee(6);//父类类名重载静态方法调用
}
int main()
{
test();
return 0;
}