本文主要是介绍类的练习:定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
定义一个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;
}
小结
对于类的构造函数内部进行细小优化,用了一下构造函数,如果就用普通函数只能完成赋值行为。
优化失败,我是菜狗我自己爬
这篇关于类的练习:定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!