有这么三个类函数
class IA { public: virtual void func1() = 0; virtual void func2() = 0; }; class B : public IA { public: B(); virtual void func1(); virtual void func2(); void func3(); static void func4(); protected: void printMember(); protected: int m_protected; private: int m_private; }; class C : public B { public: C(); virtual void func1(); void func3(); private: void printMember(); private: int m_private; };
A是抽象类,B是基类,C是派生类spa
实现代码:指针
B::B():m_protected(1),m_private(2) { printf("B constructor\n"); } void B::func1() { printf("B::func1\n"); } void B::func2() { printf("B::func2 \n"); } void B::func3() { printf("B::func3\n"); printMember(); } void B::func4() { printf("B::func4\n"); } void B::printMember() { printf("B m_protected:%d\n", m_protected); printf("B m_private:%d\n", m_private); } C::C():m_private(3) { printf("C constructor\n"); } void C::func1() { printf("C::func1\n"); } void C::func3() { printf("C::func3\n"); printMember(); } void C::printMember() { printf("C m_protected:%d\n", m_protected); printf("C m_private:%d\n", m_private); }
问题:基类和派生类的继承关系code
三种不一样方式继承的基类和派生类继承关系对象
public | protected | private | |
共有继承 | public | protected | 不可见 |
私有继承 | private | private | 不可见 |
保护继承 | protected | protected | 不可见 |
考虑如下函数:继承
C *c = new C(); c->func1(); // #2 派生类重写基类func1函数 c->func2(); // #3 继承基类函数 c->func3(); // #4 基类派生类同名函数 C::func4(); // #5 继承基类函数 delete c;
函数输出:ci
B constructor C constructor C::func1 B::func2 C::func3 C m_protected:1 C m_private:3 B::func4
派生类C继承基类的公共成员函数func2,静态成员函数func4,成员变量m_protected。table
私有成员函数和私有成员变量不继承。class
同名(同参数)函数不继承。变量
问题:基类指针指向派生类对象
考虑如下函数
B *b = new C(); b->func1(); // #2 派生类重写基类虚函数,此时指向派生类的函数实现 b->func2(); // #3 派生类没有重写基类虚函数,此时指向基类的函数实现 b->func3(); // #4 基类和派生类同名函数,调用的是基类的函数。 B::func4(); delete b;
函数输出:
B constructor C constructor C::func1 B::func2 B::func3 B m_protected:1 B m_private:2 B::func4