题目
定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。
代码
#include<iostream>
using namespace std;
#include<iomanip>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<cstring>
#include<cstdlib>
#include<cmath>
class tree
{
public:
tree(int nage=0);
void grow(int years);
void age();
private:
int ages;
};
tree::tree(int nage)
{
cout << "Please enter the tree age " << endl;
cin >> nage;
ages=nage;
}
void tree::grow(int years)
{
ages=ages+years;
}
void tree::age()
{
cout << ages;
}
int main()
{
ios_base::sync_with_stdio(0);
tree a;
int i;
cout << "Please enter the age of the tree to grow:" << endl;
cin >> i;
a.grow(i);
cout << "The age of the tree is:" << endl;
a.age();
return 0;
}
小结
对于类的构造函数内部进行细小优化,用了一下构造函数,如果就用普通函数只能完成赋值行为。
优化失败,我是菜狗我自己爬