# C++程式設計期中考複習
###### tags: `C++程式練習`
>存成c.pp檔
## C++ 基本內容:
* 整數 int long : 32位元
* 整數 long long int : 64位元
* 浮點數 float , double
>cin,cout ,iostream,stdexcept,cmath,namespace,iomanip
* 類別與物件
* 類別:總體(概念性)
* 物件:個體(實體性)
## C++切檔案(三片)
### 類別定義(.h檔)
class Temp
{
friend void fun(Temp &,int); //
public:
Temp();
Temp(const Temp &);
private:
int data1;
float data2;
};
> 存成 temp.h 檔
:::success
friend 可以讓 函式 使用 物件 裡的 private參數.
:::
### 類別實作(.cpp檔)
> 讀入 temp.h 檔
#include "temp.h"
Temp::Temp():data1(0),data2(0.0){}
Temp::Temp(const Temp &t)
{
this -> data1 = t.data1;
this -> data2 = t.data2;
}
> 存成 temp.cpp 檔
### 主程式(main())
> 讀入 temp.cpp 檔
# include <iostream>
# include "Temp.cpp"
void fun(Temp &t, int n)
{
t.data1 = n;
}
int main()
{
Temp *t = new Temp();
fun(*t ,100);
}
> 存檔為main.cpp
## C++ 輸出格式
> setw(5):設定輸出格式有幾位(5)
> setfill(' '):將未滿設定位數的以(空格)補齊
```gherkin=
#include <iomanip>
#include <iostream>
using manespace std;
int main()
{
int number;
cin >> number;
cout << setfill( 'x' ) << setw( 5 ) << number<<endl;
}
```
> setprecision(4) : 設定輸出的位數(4)
> fixed : 寫在輸出資料前,限制小數位數(取小數點後4位)
``` gherkin=
#include <iostream>
#include <iomanip>
using namespace std;
int main(void)
{
double X,Y;
cin >> X >> Y;
cout << setprecision(6) << fixed << X/Y << endl ;
return 0;
}
```
## control flow example
> countine : 跳過本次迴圈接下來執行的程式,進入下一次的迴圈
> break : 直接跳出程式中最近的迴圈
``` gherkin=
#include <iostream>
using namespace std;
class Grade{
public:
Grade():size(0),sum(0){}
void setGrade(int x){
grade[size++]=x;
}
void computeSum(){
for(int i=0;i<size;i++){
sum=sum+grade[i];
}
}
float retAvg(){
if(size!=0) return (float)sum/size;
else return -1.0;
}
void printAvg(){
float avg = retAvg();
if((avg<0) cout<<"No valid grade is entered"<<endl;
else cout<<"The averaged score is: "<<avg<<endl;
}
private:
int grade[1000],size,sum;
};
int main(){
Grade g1;
int grade;
for(;;){
cout<<"Enter a grade: "<<endl;
cin>>grade;
if(grade==-1)break;
if((grade<0) || (grade>100))continue;
g1.setGrade(grade);
}
g1.computeSum();
g1.printAvg();
return 0;
}
```
## template< typename T > 模板使用
``` gherkin=
#include <iostream>
using namespace std;
template <typename R,typename M>
void bank(M money,R rate)
{
cout << money * rate<<endl;;
}
int main()
{
int a=1000,b=2;
float c=1.1,d=2345.1;
bank(a,b);
bank(a,c);
bank(d,c);
bank(d,b);
return 0;
}
```
>寫一個函式做陣列的加總,不限資料型態。
template <typename T>
T sum(T *arr, int len) {
T ans ;
for(int i =0; i<len;i++)
{
ans += arr[i];
}
return ans;
}
> 設計一template function 將陣列由小到大排序
``` gherskin=
template <typename T>
void sort(T arr[], int len)
{
for(int i =0;i<len-1;i++)
{
for(int j=1;j<len;j++)
{
if(arr[j] < arr[j-1])
{
T temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
```
## throw 出錯誤訊息
> stdexcept 語法 : throw,try,catch
``` gherskin=
#include <iostream>
#include <iomanip>
#include <stdexcept> // for invalid_argument exception class
using namespace std;
class test
{
public:
void setGrade( int x )
{
// validate grade
if ( x >= 0 && x <=100 ){
grade=x;
}
else
throw invalid_argument("invalid grade");
}
void printGrade(){
cout << setfill( '0' ) << setw( 3 ) << grade<<endl;
}
private:
int grade;
};
int main()
{
test t,*tptr=&t,&reft=t;
int g;
cout<<"Enter a grade"<<endl;
cin>>g;
try
{
t.setGrade( g );
t.printGrade();
}
catch ( invalid_argument &e )
{
cout << "\n\nException: " << e.what() << endl; }
cout<<"Enter a grade"<<endl;
cin>>g;
try
{
tptr->setGrade( g );
tptr->printGrade();
}
catch ( invalid_argument &e )
{
cout << "\n\nException: " << e.what() << endl;
}
cout<<"Enter a grade"<<endl;
cin>>g;
try
{
reft.setGrade( g );
reft.printGrade();
}
catch ( invalid_argument &e )
{
cout << "\n\nException: " << e.what() << endl;
}
}
```
## friend function 應用
``` gherskin=
#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
friend void setT(Time &,int,int,int); // friend declaration
friend void getT(Time &);
private:
int hour,minute,second; // data member
};
void setT( Time &c, int h, int m, int s )
{
c.hour=h;
c.minute=m;
c.second=s;
}
void getT( Time &c)
{
cout<<setfill('0')<<setw(2)<<c.hour<<":";
cout<<setw(2)<<c.minute<<":";
cout<<setw(2)<<c.second<<endl;
}
int main()
{
Time t;
setT(t,1,1,1); // set time using a friend function
getT(t); //get time using a friend function
return 0;
}
```
## recursive 遞迴實作