C++小练习
1.定义Boat与Car两个类,二者都有weight属性,
定义两者的一个友原函数getTotalWeight(),
计算二者的重量和。
class Car; class Boat { public: int weight; friend int getTotalWeight(Boat &boat, Car &car); Boat(int a):weight(a){} }; class Car { public: int weight; friend int getTotalWeight(Boat &boat, Car &Car); Car(int a):weight(a){} }; int getTotalWeight(Boat &boat, Car &Car) { return boat.weight + Car.weight; } void main() { Boat A(100); Car B(20); cout<<"两者的重量总和:"<<endl; cout<<getTotalWeight(A,B)<<endl; }
2.声明一个Cat类,拥有静态成员catnum,记录Cat的个体数目;
声明静态成员函数GetHowMany(),存取catnum。
设计程序测试这个类,体会静态数据成员和静态成员函数的用法。
class Cat { public: Cat(){++catnum;} Cat(const Cat& cat){++catnum;} virtual ~Cat(){--catnum;} static int GetHowMany(){return catnum;} private: static int catnum; }; int Cat::catnum=0; int main() { Cat a; Cat b; cout<<"catnum:"<<Cat::GetHowMany()<<endl; Cat c(a); Cat* p=new Cat(); cout<<"catnum:"<<Cat::GetHowMany()<<endl; delete p; cout<<"catnum:"<<Cat::GetHowMany()<<endl; return 0; }