- 定义一个shape类,在此基类基础上派生Rectangele 和circle类,二者都有getarea()函数计算对象的面积,使用Rectangele 类创建一个派生类square类。
#include<iostream>
using namespace std;
class shape{
public:
virtual double getarea() = 0;
};
class Rectangle :public shape{
private:
double longth;
double width;
public:
Rectangle(double a, double b){
longth = a;
width = b;
}
~Rectangle(){
cout << "Rectangle释放" << endl;
}
double getarea(){
return longth * width;
}
};
class circle :public shape{
private:
double r;
public:
circle(double a){
r = a;
}
~circle(){
cout << "circle释放" << endl;
}
double getarea(){
return 3.14 * r * r;
}
};
class Square :public Rectangle{
public:
Square(double aa) :Rectangle(aa, aa) {}
~Square(){
cout << "Square释放" << endl;
}
};
int main(){
Rectangle A(1, 2);
cout << A.getarea() << endl;
circle B(2);
cout << B.getarea() << endl;
Square C(3);
cout << C.getarea() << endl;
return 0;
}
- 定义一个基类Base,有两个公有成员fn1(),fn2(),私有派生出Derived类,如何通过Derived类的对象调用基类的函数fn1()?
#include<iostream>
using namespace std;
class Base{
public:
void fn1() {
cout << "Base::fn1" << endl;
}
void fn2() {
cout << "Base::fn2" << endl;
}
};
class Derived :private Base {
public:
void bfn1() {
cout << "Derived,";
fn1();
}
void bfn2() {
cout << "Derived,";
fn2();
}
};
int main(){
Derived d;
d.bfn1();
return 0;
}
- 定义一个Object类,有数据成员weight及相应的操作函数,由此派生出Box类,增加数据成员height和width及相应操作函数,声明一个Box对象,观察构造函数与析构函数的调用顺序。
略
- 分别用Derived的对象以及Base和Derived的指针来调用fn1();和fn2();
int main(){
Derived d;
d.bfn1();
d.bfn2();
Derived* pd = &d;
pd->bfn1();
pd->bfn2();
Base b;
Base* pb = &b;
pb->fn1();
pb->fn2();
return 0;
}
- 思考派生类的各数据成员在对象中的存放位置,编写程序输出他们各自的地址来验证自己的推断。
#include<iostream>
using namespace std;
class Base{
public:
string name;
};
class Derived :public Base {
public:
int pageCount;
};
int main(){
Derived d;
Derived* pd = &d;
Base* pb = pd;
cout << "派生类对象的地址:" << &pd << endl;
cout << "基类对象的地址:" << &pb << endl;
cout << "基类指向:" << pb << endl;
cout << "name的地址:" << &(pb->name) << endl;
cout << "pageCount的地址:" << &(pd->pageCount) << endl;
return 0;
}
运行结果:
派生类对象的地址:010FFA10
基类对象的地址:010FFA04
基类指向:010FFA1C
name的地址:010FFA1C
pageCount的地址:010FFA38
- void指针不能这么用:
#include<iostream>
using namespace std;
struct Base1 { int x; };
struct Base2 { float y; };
struct Derived :Base1, Base2 { };
int main(){
Derived* pd = new Derived;
pd->x = 1; pd->y = 2.0f;
void* pv = pd;
Base2* pb = static_cast<Base2*>(pv);
cout << pd->y << endl << pb -> y << endl;
delete pd;
return 0;
}
运行结果:
2
1.4013e-45
代码改成这样运行结果也是一样的:
#include<iostream>
using namespace std;
class Base1 { public: int x; };
class Base2 { public: float y; };
class Derived :public Base1, public Base2 { };
int main(){
Derived* pd = new Derived;
pd->x = 1; pd->y = 2.0f;
void* pv = pd;
Base2* pb = static_cast<Base2*>(pv);
cout << pd->y << endl << pb -> y << endl;
delete pd;
return 0;
}