?? grass.cpp
字號:
//-----------------------------grass.cpp-------------------------------
#include <iostream>
using namespace std;
#include "grass.h"
grass::grass(int height)
{
this->height=height; //對于任何一個對象的方法來說,this永遠是一個指向這個
//對象的指針。所以這樣寫能使編譯器知道是類中的height
}
//下面對類的方法進行定義
void grass::cut( ) // "::"表示cut( )是grass的成員。
{
if (height>=10)
height-=10; //可自由訪問grass中的任何成員。
}
void grass::water( )
{
height+=10;
}
int grass::get_height( ) //在類的外部不能直接訪問height,所以要寫這個函數(shù)
{
return height;
}
void grass::set_height(int newh) //同樣我們寫了這個函數(shù)
{
if (newh>=0)
height=newh;
}
void main( )
{
grass grass1,grass2; //其實這一句和"int a,b;"沒什么區(qū)別,想一想!這一句語
//句被稱為實例化。
grass1.set_height(20); //如果你用過VB一定會覺得很親切。類以外的函數(shù)即使
//是訪問類的公有部分也要用"."。
cout<<grass1.get_height( )<<endl;
grass1.set_height(-100); //因為set_height作了保護措施,所以這一句不會給
//height一個荒唐的值
cout<<grass1.get_height( )<<endl;
grass1.cut( );
cout<<grass1.get_height( )<<endl;
grass2=grass1; //同一種對象可直接互相賦值
cout<<grass2.get_height( )<<endl;
grass *grass3; //也可定義指向類的指針
grass3=new grass; //同樣要new
grass3->set_height(40); //由于grass3是指針,這里要用"->"。其實也可以
//使用(*grass3).set_height(40); ("."操作符比"*"
//操作符執(zhí)行時優(yōu)先) ,不過這樣寫比較麻煩。
grass3->water( );
cout<<grass3->get_height( );
delete grass3; //釋放指針
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -