1.c++ 基础知识-类和对象-继承-构造和析构顺序
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base();
~Base();
};
Base::Base()
{
cout<<"Base():构造函数"<<endl;
}
Base::~Base()
{
cout<<"Base():析构函数"<<endl;
}
class A:public Base
{
public:
A();
~A();
};
A::A()
{
cout<<"A():构造函数"<<endl;
}
A::~A()
{
cout<<"A():析构函数"<<endl;
}
void fun_A()
{
A a;
}
int main()
{
fun_A();
return 0;
}
2.c++ 基础知识-类和对象-继承-同名成员处理
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base();
void fun();
void fun(int n);
int m_A;
};
Base::Base()
{
m_A = 2000;
}
void Base::fun()
{
cout<<"Base : fun()"<<endl;
}
void Base::fun(int n)
{
cout<<"n = "<<n<<endl;
cout<<"Base:fun(int n)"<<endl;
}
class A:public Base
{
public:
A();
void fun();
int m_A;
};
A::A()
{
m_A = 100;
}
void A::fun()
{
cout<<"A : fun()"<<endl;
}
void fun_A()
{
A a;
cout<<a.m_A<<endl;
cout<<a.Base::m_A<<endl;
a.fun();
a.Base::fun();
a.Base::fun(4);
}
int main()
{
fun_A();
return 0;
}
注意,同名静态成员处理方式和非静态处理方式一样,只不过有两种访问的方式(通过对象和类名)
static void fun();
static void fun();
A::Base::fun();
a.Base::fun();
3.c++ 基础知识-类和对象-继承-多继承
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base();
int m_A;
};
Base::Base()
{
m_A = 2000;
}
class Base1
{
public:
Base1();
int m_B;
};
Base1::Base1()
{
m_B = 22222;
}
class A:public Base,public Base1
{
public:
A();
int m_C;
};
A::A()
{
m_C = 10000;
}
void fun()
{
A a;
cout<<sizeof(a)<<endl;
cout<<a.m_A<<endl;
cout<<a.m_B<<endl;
cout<<a.m_C<<endl;
}
int main()
{
fun();
return 0;
}
4.c++ 基础知识-类和对象-继承-菱型继承
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base();
int m_number;
};
Base::Base()
{
m_number = 2000;
}
class Left : virtual public Base
{
};
class Right : virtual public Base
{
};
class Test:public Left,public Right
{
};
void fun()
{
Test t;
t.Left::m_number = 18;
t.Right::m_number = 28;
cout<<t.Left::m_number<<endl;
cout<<t.Right::m_number<<endl;
cout<<t.m_number<<endl;
}
int main()
{
fun();
return 0;
}