?? 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()//缺省構(gòu)造函數(shù)
{
name="noname";
age=0;
color="unknown";
weight=0;
write<<endl;
write<<"constructor pet";//顯示構(gòu)造函數(shù)被調(diào)用,下同
}
pet(string n,int a,string c,float w)//重載構(gòu)造函數(shù),輸入所有屬性
{
name=n;
age=a;
color=c;
weight=w;
write<<endl;
write<<"constructor pet";
}
~pet()//析構(gòu)函數(shù),可寫可不寫
{
write<<endl;
write<<"destructor pet";//顯示析構(gòu)函數(shù)被調(diào)用,下同
}
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()//缺省構(gòu)造函數(shù)
{
sleeptime=0;
write<<endl;
write<<"constructor cat";
}
cat(string n,int a,string c,float w,float s):pet(n,a,c,w)//重載構(gòu)造函數(shù),輸入所有屬性(包括基類中定義的)
{
sleeptime=s;
write<<endl;
write<<"constructor cat";
}
~cat()//析構(gòu)函數(shù),可寫可不寫
{
write<<endl;
write<<"destructor cat";
}
float get_sleeptime(){return sleeptime;}
void print()
{
pet::print();//調(diào)用基類打印函數(shù)
write<<sleeptime<<" hours, ";
}
};
/*附:整個程序主要為測試使用,提交作業(yè)時將本行以上寫出即可;
constructor xxx 和 destructor xxx 便于分析構(gòu)造函數(shù)與析構(gòu)函數(shù)被調(diào)用的順序,可刪掉;
若不是用于教學(xué)和應(yīng)付考試,析構(gòu)函數(shù)可刪掉;
程序執(zhí)行結(jié)束,所有屬性和函數(shù)調(diào)用信息將保存在E:\\attribute.txt
*/
void main()
{
pet p1;//定義寵物類p1,調(diào)用缺省構(gòu)造函數(shù)
p1.print();
pet p2("dd",10,"red",5);//定義寵物類p2,調(diào)用重載的構(gòu)造函數(shù)
p2.print();
cat c1;//定義子類貓c1,調(diào)用缺省構(gòu)造函數(shù)
c1.print();
cat c2("zZ",11,"yellow",6,12);//定義子類貓c2,調(diào)用重載的構(gòu)造函數(shù)
c2.print();
cout<<"OK"<<endl;
string temp;
temp=p1.get_name();//temp通過成員函數(shù)接收私有變量
write<<endl;
write<<temp;//輸出至文件,測試效果
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -