类的练习:定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。
生活随笔
收集整理的這篇文章主要介紹了
类的练习:定义一个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的值。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: u-boot简单学习笔记(二)——AR9
- 下一篇: 手机银行元的符号¥在某些机型上展示少了一