动物和狗 - C/C++ 代码复用
分数 10
请将后续代码补充完整,使其满足下述要求,并可得到期望的运行结果。
- 设计动物基类Animal,包括体重、脚的数量等数据成员;
- 从Animal扩展出子类Dog,添加名字等数据成员;
- 为两个类添加带有信息输出的构造函数以及析构函数,观察当一个Dog对象被创建时,子类与父类构造函数的执行顺序;
- 观察当一个Dog对象被析构时,子类与父类析构函数的执行顺序;
- 打印输出一个Dog对象的地址以及子类对象中父对象的地址,分析Dog对象的内存结构。
-
#include<iostream>
#include<string.h>
using namespace std;
class Animal{
public:
int iFeetCount{0};
int iWeight{0};Animal(){
cout<<"Animal(), weight = "<< iWeight << endl;
}
~Animal(){
cout<<"~Animal(), weight = "<< iWeight << endl;
}
};
class Dog : public Animal{
public:
string sName;
Dog(const string name,int weight ){
sName = name;
iFeetCount = 4;
iWeight = weight;
cout<<"Dog(), name = "<< name <<", weight = "<< iWeight << endl;
}
~Dog(){
cout <<"Dog() ,name = "<< sName <<", weight = "<< iWeight << endl;
}
};
int main()
{
Dog* d1 = new Dog("Bottle",3100);
delete d1;
cout<<"---------------------------------------"<<endl;
Dog* d2 = new Dog("Nauty",2312);
Animal* a2 = d2;
if (a2==d2);
cout << "Parent object is located at the beginning of sub object."<<endl;
delete d2;
return 0;
}
2974

被折叠的 条评论
为什么被折叠?



