//程式很簡單,相信大家都會,也會比好寫的好。我寫的很爛.........................
//不過有幾個地方相信初學者,剛開始學習跟我一樣有點迷糊。
#include<iostream>
using namespace std;
const int SIZE=15;
class point
{
private:
const int size; //這裡在類的私人資料中定義了常量
char *pf;
int d;
long zs,suz;
long double xs,sus;
static long h; //這裡定義了待用資料
static long double r;
bool fund() //尋找小數點並查看字串是否包含非法字元
{
for(int i=0;i<size;i++)
{
if(pf[i]<='9'&&pf[i]>='0'||pf[i]=='.')
{
if(pf[i]=='.') d=i;
else if(i==size-1) return true;
}
else return false;
}
}
void funz() //把小數點前的轉換成數字並相加
{
for(int i=d-1;i>=0;i--)
{
zs=(pf[i]-'0')*h;
suz+=zs;
h*=10;
}
}
void funx()// 把小數點後的部分轉換並相加
{
for(int i=d+1;i<size;i++)
{
xs=(pf[i]-'0')*r;
sus+=xs;
r*=0.1;
}
}
long double funh() //判斷是否有異常,並返回計算結果
{
cout.setf(ios_base::fixed,ios_base::floatfield); //採用定點輸出,也就是不讓c++在double值到百萬位是自動轉換成e格式。
cout.precision(4); //保留4位小數
if(fund())
{
if(d==0)
{
d=size;
funz();
}
else
{
funz();
funx();
}
return suz+sus;
}
else
{
cout<<"有非法字元";exit(1);
}
}
public:
point(char *pt=0):pf(new char[strlen(pt)+1]),size(strlen(pt)) //這裡採用了成員初始化列表的句法
{
d=0;
zs=suz=0;
xs=sus=0.0;
strcpy(pf,pt);
}
friend ostream& operator<<(ostream& os, point& shzi)
{
os<<shzi.funh();
return os;
}
~point() { delete[]pf; }
};
long point::h=1; //這裡初始化了靜態成員變數 ,
long double point::r=0.1;
int main()
{
char str[SIZE];
cin.get(str,SIZE-1);
str[SIZE-1]=0;
while(cin.get()!='/n')continue;
cin.clear();
point wyz(str);
cout<<wyz;
return 0;
}
不能在類聲名中初始化靜態成員變數,這是因為聲名描述了如何分配記憶體,但並不分配記憶體。但可以使用這種格式來建立對象,從而分配和初始化記憶體。
對於靜態成員可以在類聲名之外使用單獨語句初始化,這是因為靜態類成員是單獨儲存的,而不是對象的組成部分。請注意,初始化語句指出類型,並使用了範圍操作符。
對於不能在類聲名中初始化待用資料成員的一種例外情況是,待用資料成員為整型或枚舉型const。
.................
成員初始化列表的句法只能用於建構函式。
必須用這種格式初始化非靜態const資料成員。
必須用這種格式初始化引用資料成員。