十.继承
1.Code
:
#include<iostream>
using namespace std;
class cat
{
public:
cat()
{
cout << "cat 构造函数" << endl;
}
~cat()
{
cout << "cat 析构函数" << endl;
}
int func()
{
cout << "cat 下的 func" << endl;
return 0;
}
int a = 0;
protected:
int b = 0;
private:
int c = 0;
};
class cat1 : public cat
{
public:
cat1()
{
cout << "cat1 构造函数" << endl;
}
~cat1()
{
cout << "cat1 析构函数" << endl;
}
int func()
{
cout << "cat1 下的 func" << endl;
return 0;
}
int a = 1;
};
void test()
{
cat1 c1;
cout << "sizeof(cat1) = " << sizeof(cat1) << "byte" << endl;
}
void test1()
{
cat1 c1;
cout << "cat1下的a " << c1.a << endl;
cout << "cat 下的a " << c1.cat::a << endl;
cout << c1.func() << endl;
cout << c1.cat::func() << endl;
}
class Base {
public:
static void func()
{
cout << "Base - static void func()" << endl;
}
static void func(int a)
{
cout << "Base - static void func(int a)" << endl;
}
static int m_A;
};
int Base::m_A = 100;
class Son : public Base {
public:
static void func()
{
cout << "Son - static void func()" << endl;
}
static int m_A;
};
int Son::m_A = 100;
void test2()
{
cout << "通过对象访问: " << endl;
Son s;
cout << "Son 下 m_A = " << s.m_A << endl;
cout << "Base 下 m_A = " << s.Base::m_A << endl;
s.func();
cout << "通过类名访问: " << endl;
cout << "Son 下 m_A = " << Son::m_A << endl;
cout << "Base 下 m_A = " << Son::Base::m_A << endl;
}
class A
{
public:
int aa = 1;
};
class A1 : virtual public A
{
public:
int aa1 = 2;
};
class A2 : virtual public A
{
public:
int aa2 = 3;
};
class B : public A1,public A2
{
public:
int bb = 2;
};
void test3()
{
B b1;
b1.A1::aa = 100;
b1.A2::aa = 200;
cout << "b1.A1::aa = " << b1.A1::aa << endl;
cout << "b1.A2::aa = " << b1.A2::aa << endl;
cout << " b1.aa = " << b1.aa << endl;
}
int main()
{
test();
cout << "二. 访问成员函数" << endl;
test1();
cout << "三. 继承同名静态成员处理方式" << endl;
test2();
cout << "五. 菱形继承" << endl;
test3();
system("pause");
return 0;
}
2.运行结果
:
