4-8
定义一个Dog 类,包含的age、weight等属性,以及对这些属性操作的方法。实现并测试这个类。
#include <iostream>
using namespace std;
class Dog
{
public:
Dog (int Age0 = 0,int Weight0 = 5);
~Dog();
int GetAge() { return Age1;}
void SetAge (int age) { Age1 = age;}
int GetWeight() { return Weight1;}
void SetWeight (int weight) { Age1 = weight;}
int Age1,Weight1;
};
Dog::Dog(int Age0, int Weight0)
{
Age1 = Age0;
Weight1 = Weight0;
}
Dog::~Dog() //destructor, takes no action
{
}
int main()
{
Dog cindy(1,10);
cout << "cindy 是一条狗 " ;
cout <<"她"<< cindy.GetAge() << " 岁了";
cout <<"有"<< cindy.GetWeight() << " 有公斤重\n";
cindy.SetAge(7);
cindy.SetWeight(20);
cout << "现在 cindy 已经 " ;
cout << cindy.GetAge() << " 岁了";
cout <<"有"<< cindy.GetWeight() << " 公斤重.";
return 0;
}
程序运行结果: