📄 pet.cpp
字号:
#include<iostream.h>
#include<string.h>
#include<fstream>
#include<iomanip.h>
#include<sstream>
using namespace std;
ofstream write("E:\\attribute.txt"); //定义输出文件流
/*宠物类*/
class pet
{
private:
string name;
int age;
string color;
float weight;
public:
pet()//缺省构造函数
{
name="noname";
age=0;
color="unknown";
weight=0;
write<<endl;
write<<"constructor pet";//显示构造函数被调用,下同
}
pet(string n,int a,string c,float w)//重载构造函数,输入所有属性
{
name=n;
age=a;
color=c;
weight=w;
write<<endl;
write<<"constructor pet";
}
~pet()//析构函数,可写可不写
{
write<<endl;
write<<"destructor pet";//显示析构函数被调用,下同
}
string get_name(){return name;}//获取私有变量
int get_age(){return age;}
string get_color(){return color;}
float get_weight(){return weight;}
void print()//打印至文件
{
write<<endl;
write<<name<<", "<<age<<" years old, "<<color<<", "<<weight<<"kg, ";
}
};
/*子类--猫*/
class cat:public pet
{
private:
float sleeptime;
public:
cat()//缺省构造函数
{
sleeptime=0;
write<<endl;
write<<"constructor cat";
}
cat(string n,int a,string c,float w,float s):pet(n,a,c,w)//重载构造函数,输入所有属性(包括基类中定义的)
{
sleeptime=s;
write<<endl;
write<<"constructor cat";
}
~cat()//析构函数,可写可不写
{
write<<endl;
write<<"destructor cat";
}
float get_sleeptime(){return sleeptime;}
void print()
{
pet::print();//调用基类打印函数
write<<sleeptime<<" hours, ";
}
};
/*附:整个程序主要为测试使用,提交作业时将本行以上写出即可;
constructor xxx 和 destructor xxx 便于分析构造函数与析构函数被调用的顺序,可删掉;
若不是用于教学和应付考试,析构函数可删掉;
程序执行结束,所有属性和函数调用信息将保存在E:\\attribute.txt
*/
void main()
{
pet p1;//定义宠物类p1,调用缺省构造函数
p1.print();
pet p2("dd",10,"red",5);//定义宠物类p2,调用重载的构造函数
p2.print();
cat c1;//定义子类猫c1,调用缺省构造函数
c1.print();
cat c2("zZ",11,"yellow",6,12);//定义子类猫c2,调用重载的构造函数
c2.print();
cout<<"OK"<<endl;
string temp;
temp=p1.get_name();//temp通过成员函数接收私有变量
write<<endl;
write<<temp;//输出至文件,测试效果
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -