NJUPT【 面向對象程序設計及C++ 】

Part 1/6 考試范圍

第1章
面向對象的三大特征,類和對象,程序開發過程
第2章
cin、cout,::,全局變量,定義函數時形參帶有默認值,函數重載
引用,利用指針動態內存空間管理,try catch throw機制的異常處理方式
第3章
類的定義,對象的定義,this指針,構造函數,復制構造函數,析構函數,對象數組,對象指針、對象引用、對象參數
第4章
對象成員,常數據成員,常對象,常成員函數,友元函數、友元成員、友元類
第5章
類的繼承與派生,private、protected、public,定義派生類對象時,構造函數的調用順序,同名沖突,賦值兼容的四種情況
第6章
靜態多態性、動態多態性,運算符重載,友元重載,成員函數重載,輸入/輸出流重載:ostream & 和 istream &,虛函數的定義,純虛函數和抽象類
第7章
函數模板的定義及調用,函數模板的重載,類模板的定義及調用
第8章
文件的分類,open打開方文件,ios::in 讀文件, ios::out 寫文件,close關閉文件
運算符>>和<<對文件操作,get、put函數,read、write函數

Part 2/6 考試真題

第7題

Part 3/6 練習題庫

第1章 C++語言概述

  • 課后習題

①面向對象語言:C++,Java,Python
②類是類型,對象是類類型變量,類型不占有內存,變量占有內存
③面向對象特征:封裝性,繼承性,多態性
④對象是是類類型變量,不是結構體變量

第2章 對C的改進及擴展

  • 課后習題

①int y[n];中n必須為常量,int *py=new int[n];中n可以為常量和變量
②int add(int x,int y=4,int z=5);默認值的函數原型聲明從右往左
③重載函數滿足,形參的個數或類型或順序不同
int a(int x);和int a(float x);
int b(int x,char *s);和int b(char *s,int x);
int c(int x);和int c(int x,int y);
而int d(int x); 和 char *d(int y); 不是重載
④int *p=new int;(一維數組)int *p=new int(10);(一維數組賦值)
int *p=new int[10];(10個元素)int *p=new int[10] (10);(錯誤語句)
⑤int x=1,y=2,&z=x;執行z=y后,x=z=y=2

  • 平臺習題

①全局變量 x 在main函數中可以訪問,形如:“::x = 1;” 使其獲得新的值1
②使用delete運算符釋放所申請的動態內存空間
③為名空間ABC變量x賦值:
ABC::x = 10;
using namespace ABC; x = 10;
using ABC::x ; x = 10;
④運算符<<:
用于輸出的插入符
左移位運算符
右邊可以是表達式,變量
⑤關于try-catch:
語句塊必須一起出現,缺一不可,且try塊在先catch塊在后
如果有try塊,可以有多個,與try塊對應的catch塊可以有多個
⑥const char *;表示不能改指針,const name="abc";表示不能改name
⑦const char *ptr; 定義一個指向字符常量的指針
char const *ptr; 定義一個指向字符常量的指針
char * const; 定義一個指向字符的指針常數
⑧內聯函數:
在編譯時目標代碼將插入每個調用該函數的地方
一般代碼較短,而且調用較頻繁
函數體內一般不能有開關語句及循環語句

第3章 類與對象1

  • 課后習題

①類定義結束以“ ; ”結束
②Time( int=0, int=0, int=0)有三個形參
③class類沒有關鍵字public,private,protected時,訪問屬性為private
④類與對象的關系類似于數據類型與變量
任何一個對象只能屬于一個具體的類
⑤一個類只能有一個析構函數
⑥拷貝構造函數的參數是某個對象的常引用名

  • 平臺習題

①私有成員變量不能賦初值
②p是一個指向類A公有數據成員m的公有指針成員,A1是類A的一個對象
可以用*A1.p=5給m賦值為5
③類的成員函數包括:構造函數,析構函數,拷貝構造函數
而友元函數不是類的成員函數
④一個類中可以有多個構造函數
構造函數在定義對象時自動執行
構造函數名必須和類名一致
構造函數無任何函數類型
⑤有參構造函數:A (int a);
無參構造函數:A ();
拷貝構造函數:A (const A& a);
賦值構造函數:A & operator = (const A& a);
⑥析構函數是在對象生存期結束時調用的
⑦成員函數不一定是內聯函數
成員函數可以重載
成員函數可以是靜態的

第4章 類與對象2

  • 課后習題

①靜態數據成員在類外初始化
靜態數據成員是同類所有對象共有的
靜態數據成員為public,才能用類名::成員名訪問
②靜態成員函數沒有this指針
③常數據成員通過類構造函數的初始化列表進行初始化
例如:A(int a,int b):a(a),b(b)
常數據成員必須初始化,不能被更新,作用域為本類
例如:const int a=10;
④普通函數可以改變數據成員的值,常成員函數不可以改變數據成員的值
⑤常對象只能調用常函數,常函數可以被任何對象調用
void fun() const //常函數fun()
Time const t1(12,34,36); //常對象t1

class Point
{
public:
    void a() //非靜態成員函數
    { }
    static void b() //靜態成員函數
    { }
};
void main()
{
    Point pt;
    pt.a(); //通過對象調用非靜態成員函數
    pt.b(); //通過對象調用靜態成員函數
    Point::a(); //報錯 
    Point::b(); //通過類名調用靜態成員函數 
}
  • 平臺習題

①常對象是各數據成員值不可改變的對象
常對象所屬的類中也可以定義非常成員函數
②類中靜態數據成員:static int count; 為其初始化:int Test::count=10;
③靜態成員函數一般專門用來直接訪問類的靜態數據成員

第5章 繼承與派生

  • 課后習題

①派生類可以繼承多個基類,派生類對基類默認的繼承方式為private
在多層的類繼承中,中間類既是上層類的派生類又是下層類的基類
如果基類構造函數沒有形參或帶有默認值,
派生類構造函數初始化列表中就不必對基類構造函數進行調用
②多重繼承構造函數的調用順序一般可分為4個步驟:
Step 1:任何虛基類,按照它們被繼承的順序依次調用構造函數。
Step 2:任何非虛基類,按照它們被繼承的順序依次調用構造函數。
Step 3:任何派生類,按照它們聲明的順序依次調用所屬類的構造函數。
Step 4:調用派生類自己的構造函數。
③派生類構造函數的成員初始化列表,不能包含基類的成員對象所屬類的構造函數
④在定義最后派生類對象時,將引起虛基類構造函數的調用,該函數只能被調用一次

  • 平臺習題

①基類對象/引用=公有派生類對象/引用,反之不成立
基類對象的指針=公有派生類對象的指針,反之不成立
例如:B是基類A的派生類,并有A aa, *pa=&aa; B bb, *pb=&bb;
bb=aa; (錯誤語句)aa=bb; (正確語句)
*pb = *pa; (錯誤語句)pa=pb; (錯誤語句,不是指針)
②派生類是基類的特殊化,具體化,定義的延續 ,
③派生類對象d可以用d.x的形式訪問基類的成員x,則x是:公有派生的公有成員
④派生類默認繼承方式為private繼承
基類公有成員在派生類中屬性可變
對基類成員的訪問必須無二義性
賦值兼容規則也適用于多重公有繼承
⑤多重繼承中,如果基類有非私有屬性的同名成員,
在派生類引用該同名成員時可以在該同名成員前增加:“基類名:: ”來區分
⑥派生類新增加的成員函數,其父類中私有繼承的私有成員是不可直接訪問的
⑦對象成員的構造函數由所在類的構造函數來調用
對象成員的訪問類型可以使用任何類型
對象成員如果是公有類型也可以被繼承
對象成員中的成員可以被所在類的成員函數訪問
⑧在最后派生類構造函數的調用中,
先調用虛基類的構造函數,再調用其它基類的構造函數時,不再調用虛基類的構造函數。

第6章 多態性

  • 課后習題

①C++語言中有5 個運算符不能重載:.、.*、::、?:、sizeof
②重載函數要求:參數個數不同或者參數類型不同
③運算符重載不可以改變運算符的個數,優先級,結合性,語法結構
④靜態多態性可以使用函數重載和運算符重載獲得
⑤抽象類是指含有純虛函數的基類,其純虛函數由派生類實現
純虛函數是一種特殊的虛函數,它沒有具體的實現代碼
如果派生類不實現基類的純虛函數,該派生類仍然為一個抽象類

  • 平臺習題

①抽象類的特性:不能說明其對象
②動態聯編是用來在編譯時確定操作函數的
③基類中說明了虛函數后,派生類中的函數可不必說明為虛函數

第7章 模板

  • 課后習題

①函數模板:
template <class T>
T max(T x, T y)
{
return(x > y)?x : y;
}
變量int i; char c;
錯誤語句:max(i, c); 正確語句:max(i, i); max(c, c); max((int)c, i);
②模板的使用是為了提高代碼的可重用性
③函數模板:
template < class T1, class T2 >
void sum(T1 x, T2 y)
{
cout << sizeof( x+y );
}
sum('1', 99.0) 的輸出結果是:8

因為99.0為double 類型,故 sizeof( x+y ) = sizeof( double ) = 8
  • 平臺習題

①函數模板:
template <class T>
class Array
{
...
};
模板類定義:Array<int> arr(100);
②函數模版:
template <class T1, class T2>
void sum(T1 x, T2 y)
{
cout<<(x+y);
}
變量:int a; double b; char c;
錯誤語句:sum("abc", "ABC"); 正確語句:sum(a,a); sum(a,b); sum(b,c);
③函數模版:
template <class T>
T func(T x, T y)
{
return x * x + y * y;
}
正確的調用語句是: func(3,4)
④模板參數可以作為:數據成員的類型,成員函數的返回類型,成員函數的參數類型
⑤模板聲明的開始部分:template <class T1, class T2>
⑥模板的使用目的:提高代碼的可重用性

第8章 文件及輸入輸出

  • 課后習題

①執行文件輸入/輸出的操作,需要在程序中包含頭文件名字空間 std 的 fstream 文件
②打開文件時,文件的所有使用方式:
ios::app // 輸出到尾部
ios::ate // 尋找文件尾
ios::in // 文件輸入
ios::out // 文件輸出
ios::trunc // 刪除同名文件
ios::binary // 二進制方式打開
ios::nocreate // 若文件不存在,則open()函數失敗
ios::noreplace // 若文件存在,則open()函數失敗
對于 ifstream 流,缺省值為 ios::in
對于 ofstream 流,缺省值為 ios::out
③在ios 類中控制格式的標志位中:
dec、oct、hex 分別是10進制、8進制、16進制的標志位
showbase 表示輸出數值前面帶有基數符號
④getline()、read() 和 get() 是讀操作的函數,put() 是寫操作的函數
⑤istream & istream :: seekg(long, seek_dir); 表示在輸入流中移動文件讀指針。
long 參數規定偏移量,正數表示向后移,負數表示向前移。
seek_dir 參數規定起始位置:beg:開始位置。cur:當前位置。end:結束位置。
例:已知 a 為 ifstream 流類的對象,并打開了一個文件
將對象 a 的讀指針移到當前位置后100個字節處的語句是:a.seekg(100, ios::cur);

  • 平臺習題

①float data,以二進制方式將 data 的數據寫入輸出文件流類對象 x 中去的語句是:x.write((char *)&data, sizeof(float));
②打開文件 D:\file.txt,寫入數據的語句是:fstream infile(" D:\file.txt ", ios::in | ios::out);
③read 函數的功能是從輸入流中讀取:指定若干個字符

Part 4/6 實驗報告

實驗報告一:類和對象的定義及使用
實驗題目1

#include <iostream>
#include <cstring>
using namespace std;

class BookCard
{
private:
    string id;      
    string stuName; 
    int number;     
public:
    BookCard(string i, string s, int n)
    {
        id=i;stuName=s;number=n;
    }
    BookCard()
    {
        id = "B19010250";stuName = "雪峰";number = 4;
    }
    void display()
    {
        cout << id <<' '<< stuName <<' '<< number << endl;
    } 
    bool borrow()
    {
        if (number==10)    {return false;}
        else   {number++;return true;}
    }
};
void f(BookCard &bk)
{
    if (!bk.borrow())
    {
        bk.display();
        cout << "you have borrowed 10 books,can not borrow any more!" << endl;
    }
    else
        bk.display();
}
int main()
{
    BookCard bk1("B20190620", "東平", 10), bk2;
    f(bk1);
    f(bk2);
    return 0;
}

實驗題目2

#include <iostream>
#include <cstring>
using namespace std;

class Time
{
private:
    int Hour;int Minute;int Second;
public:
    Time(int H, int M, int S)//構造函數 
    {
        Hour = H;Minute = M;Second = S;
    }
    ~Time()//析構函數 
    {
    }
    void add( )//改變 
    {
        Second++; 
    }
    void set(int H, int M, int S)//設定 
    {
        Hour = H;Minute = M;Second = S;
    }
    void PrintTime()//輸出 
    {
        cout << Hour << " : " << Minute << " : " << Second << endl;
    }
};

void f(Time *t)
{
    t-> PrintTime( );
}

int main()
{
    Time t0(9, 18, 46);
    t0.add();
    f(&t0);
    Time t1 = t0;//拷貝構造函數 
    t1.add();
    f(&t1);
    t0.set(1,2,34);
    f(&t0);
    return 0;
}

實驗題目3

#include <iostream>
#include <cstring>
using namespace std;

class Girl;
class Boy
{
private:
    string name;int age;
public:
    Boy(string n, int a)//構造函數 
    {
        name = n;age = a;
    }
    ~Boy()//析構函數 
    {
    }
    friend void VisitBoyGirl(Boy &B, Girl &G);//友元 
};
class Girl
{
private:
    string name;int age;
public:
    Girl(string n, int a)//構造函數 
    {
        name = n;age = a;
    }
    ~Girl()//析構函數 
    {
    }
    friend void VisitBoyGirl(Boy &B, Girl &G);//友元 
};
void VisitBoyGirl(Boy &B, Girl &G)//頂層函數 
{
    cout << "Boy:" << B.name << " " << B.age << endl;
    cout << "Girl:" << G.name << " " << G.age << endl;
}
int main()
{
    Boy B("劉林峰",16);
    Girl G("張三",18);
    VisitBoyGirl(B,G);
    return 0;
}

實驗報告二:繼承與派生實驗
實驗題目1

#include <iostream>
#include <cstring>
using namespace std;

class Vehicle
{   
public:
    int number;
    Vehicle(int n):number(n)//構造
    {cout<<"構造Vehicle"<<endl;}
    ~Vehicle( ){cout << "析構Vehicle" << endl;}//析構 
};
class Bicycle: public virtual Vehicle
{
//private: 
//protected:
public:
    string brand1;
    Bicycle(int n,string b1):Vehicle(n),brand1(b1)//構造
    {cout<<"構造Bicycle"<<endl;}
    ~Bicycle( ){cout << "析構Bicycle" << endl;}//析構 
    void disp(){cout <<brand1<<endl;}
};
class Car: public virtual Vehicle
{
public:
    string brand2;
    Car(int n,string b2):Vehicle(n),brand2(b2)//構造
    {cout<<"構造Car"<<endl;}
    ~Car( ){cout << "析構Car" << endl;}//析構 
    void disp(){cout <<brand2<<endl;}
};
class MotorCycle: public Bicycle, public Car 
{
public:
    string brand3;
    MotorCycle(int n,string x,string y,string z): Bicycle(n,x), Car(n,y),Vehicle(n),brand3(z)//構造 
    {
        cout<<"構造MotorCycle"<<endl;
        cout<<number<<" "<<brand1<<" "<<brand2<<" "<<brand3<<endl;
    }
    ~MotorCycle( ){cout << "析構MotorCycle" << endl;}//析構 
    void disp(){cout <<brand3<<endl;}
};
int main()
{
    MotorCycle a(2,"Benz","Audi","BMW");
    return 0;
}

實驗題目2

#include <iostream>
using namespace std;

class Base//基類 
{
public:
    int b;
    Base(int x): b(x){}//構造 
    void Show( ){cout<<b<<endl;}
};
class Derived: public Base//派生類 
{
public:
    int d;
    Derived(int x, int y): Base(x), d(y){}//構造 
    void Show( ){cout<<d<<endl;}
};
int  main( )
{
    Base B(11);//b=11
    Derived D(22, 33);//b=22, d=33
    
    B = D;//第一種賦值兼容
    B.Show();
    Base *B1 = &D;//第二種賦值兼容
    B1->Show(); 
    Derived *D1 = &D;//第三種賦值兼容
    Base *B2 = D1;
    B2->Show();
    Base &B3=D;//第四種賦值兼容
    B3.Show();
    return 0;
}

實驗報告三:繼承與派生實驗
實驗題目1

#include <iostream>
#include <stdlib.h>
using namespace std;

class Point    
{
private:
    double x,y;
public: 
    Point(double x=0.0,double y=0.0):x(x),y(y)//構造函數
    {  }
    Point & operator = (const Point &s)//賦值運算符 
    {
        x=s.x;
        y=s.y;
        return *this ;
    }
    Point operator + (const double b)//雙目運算符"+" 
    {
        Point tempt;
        tempt.x=this->x+b;
        tempt.y=this->y+b;
        return tempt; 
    }
    Point operator + (const Point &b)//雙目運算符"+" 
    {
        Point tempt;
        tempt.x=this->x+b.x;
        tempt.y=this->y+b.y;
        return tempt; 
    }
    Point operator ++ ( )//前置"++"運算符
    {
        ++x; ++y;
        return *this;       
    }
    friend Point operator - (const Point &a, const Point &b)//雙目運算符"-"
    {
        Point tempt;
        tempt.x=a.x-b.x;
        tempt.y=a.y-b.y;
        return tempt;  
    }
    friend ostream & operator << ( ostream &out , const Point &s)//插入運算符 
    {
        out <<"("<< s.x<<","<<s.y<<")"<<endl;   
        return out;
    }
};

int main()
{
Point pt1(10.5,20.8),pt2(-5.3,18.4),pt3;
cout<<"original pt1,pt2,pt3 are:\n";
cout<<pt1<<pt2<<pt3;
pt3=pt1+100.8;
cout<<"after pt3=pt1+100.8, pt3 is:"<<pt3;
pt3=pt1+pt2;
cout<<"after pt3=pt1+pt2, pt3 is:"<<pt3;
pt3=++pt1;
++pt2;
cout<<"after ++ pt1,pt2,pt3 are:\n";
cout<<pt1<<pt2<<pt3;
pt3=pt1-pt2;
cout<<"after pt3=pt1-pt2, pt3 is:"<<pt3;
return 0 ;
}

實驗題目2

#include <iostream>
#include <stdlib.h>
using namespace std;
const double PI = 3.1415 ;

class Container//容器 
{
public: 
    virtual double area ( ) const = 0 ;
    virtual double volume ( ) const = 0 ;
};

class Cube :public Container//正方體 
{
private:
    double a;
public:
    Cube(double a):a(a)
    { }
    double area() const
    {
        return a * a * 6;
    }
    double volume() const
    {
        return a * a * a;
    }
    void show()
    {
        cout << "正方體邊長為:" << a << " 表面積為:" << this->area() << " 體積為:" << this->volume() << endl;
    }
};

class Sphere :public Container//球體 
{
private:
    double r;
public:
    Sphere(double r):r(r) 
    { }
    double area() const
    {
        return 4 * PI * r * r;
    }
    double volume() const
    {
        return 4.0 / 3 * PI * r * r * r;
    }
    void show()
    {
        cout << "球體半徑為:" << r << " 表面積為:" << this->area() << " 體積為:" << this->volume() << endl;
    }
};

class Cylinder :public Container//圓柱體 
{
private:
    double r,h;
public:
    Cylinder(double r, double h):r(r),h(h)
    { }
    double area() const
    {
        return 2 * PI * r * h + 2 * PI * r * r;
    }
    double volume() const
    {
        return PI * r * r * h;
    }
    void show()
    {
        cout << "圓柱的底面半徑為:" << r << " 高為:" << h << " 表面積為:" << this->area() << " 體積為:" << this->volume() << endl;
    }
};

int main()
{
    Cube cu(3);
    Sphere sp(2);
    Cylinder cy(2,3);
    cu.show();
    sp.show();
    cy.show();
    return 0;
}

實驗報告四:流運算符的重載及文件的使用
實驗題目1

#include <fstream>
#include <iostream>
using namespace std;

class Course
{
private:
    string name;
    int num;
public:
    friend istream & operator >> (istream &in , Course &a )//提取運算符“>>”
    {
        in>>a.name>>a.num;
        return in;
    }  
    friend ostream & operator << (ostream &out , Course &a )//插入運算符“<<”
    {
        out<<a.name<<" "<<a.num<<endl;
        return out ;
    }   
};

int main ( )
{ 
    int count;
    Course b;
    ifstream a ( "d:\course.txt" ) ;    
    if( !a )                    
    { 
        cout << "course.txt cannot be openned!" << endl ;
        return 0 ;
    }
    char ch;
    while( a.get( ch ) )            
    {               
        a>>b;
        cout<<b;
        count++;
    }
    cout<<"記錄條數:"<<count<<endl;
    a. close( );                                        
    return 0;
}

實驗題目2

#include <fstream>
#include <iostream>
using namespace std;

void ReadFile(char *s)  
{  
    ifstream a ( s ) ;  
    if( !a )                    
    { 
        cout << s <<" cannot be openned!" << endl ;
    }
    char ch;
    while( a.get( ch ) )            
    {               
        cout<<ch;
    }
    cout<<endl;
    a. close( );  
}
void Change(char *s1,char *s2)  
{
    ifstream x (s1 ) ;  
    if( !x )                    
    { 
        cout << s1<<" cannot be openned!" << endl ;
    }
    ofstream y (s2 ) ;  
    if( !y )                        
    { 
        cout << s2<<" cannot be openned!" << endl ;
    }
    char ch;
    while( x .get( ch ) )           
    {   
        if(ch>='a'&&ch<='z')  
        {
           y.put( ch-32 ) ;     //ascii碼中大小寫相差32 
        }           
        else
        {
            y.put( ch ) ;  
        }
    }
    x. close( );                    
    y. close( );  
} 
int main ( )
{ 
    ReadFile("ff.txt");        //txt需放在當前目錄 
    Change ("ff.txt" ,"ff2.txt");
    ReadFile("ff2.txt");
    return 0;
}

實驗題目3

#include <fstream>
#include <iostream>
using namespace std;

class Student
{
private:
    char *nu;char *na;char *se;int s;//學號、姓名、性別、成績
public:
    Student(char *nu="00",char *na="null",char *se="null",int s=0):nu(nu),na(na),se(se),s(s)//構造函數 
    { }  
    friend ostream & operator<<(ostream &out,const Student &s)//重載輸出運算符<<
    {
        out<<s.nu<<" "<<s.na<<" "<<s.se<<" "<<s.s<<endl;
        return out;
    }
};

void CreateBiFile(char *filename) 
{
    ofstream out(filename);
    Student stu[3]={{"01","Tom","boy",80},{"02","Bill","boy",84},{"03","Bob","boy",90}}; //初始化信息
    out.write((char*)&stu,sizeof(stu));//二進制存儲 
    out.close( );
}
void ReadBiFile(char *filename)//讀取顯示 
{ 
    Student stu[3];
    ifstream in(filename);
    while (!in.eof( ))
    {
        in.read((char*)&stu,sizeof(stu));//二進制存儲
    } 
    for(int i=0;i<3;i++)
    {
        cout<<stu[i];
    }
    in.close( );
}

int main ( )
{ 
    CreateBiFile("stu.dat");
    ReadBiFile("stu.dat");
    return 0;
}

Part 5/6 平臺練習

第二章
0x01 動態空間管理

#include<iostream> 
using namespace std;
int main()
{
    int num,i,positive,negative;
    positive=negative=0;
    cin>>num;
    int *p=new int[20];
    for(i=0;i<num;i++)
    {
        cin>>p[i];
    }
    for(i=0;i<num;i++)
    {
        if(p[i]>0)positive++;
        if(p[i]<0)negative++;
    }
    if(num>20||num<1)cout<<"number error.\n"; 
    else
    {
        cout<<"There are "<<num<<" figures,\n"; 
        cout<<positive<<" of them are positive numbers,\n"; 
        cout<<negative<<" of them are negatives.\n";
    }
    delete []p;
    return 0;
}

0x02 求圓的面積與周長

#include<iostream> 
using namespace std;
int main()
{
    double r,s,c;
    cin>>r;
    s=3.14159*r*r;
    c=3.14159*2*r;
    cout<<"s="<<s<<",c="<<c<<endl;
    return 0;
}

第三章
0x01 簡單圖書管理

圖片.png

#include <iostream>
#include<cstring>
using namespace std;
class Book
{
private:
    string bookname;float price;int number;
public:
    Book(string name,float p,int n);
    void borrow()
    {
        number--;
    }
    void restore()
    {
        number++;
    }
    void display();
} ;
void Book::display()
{
    cout<<bookname<<" "<<price<<" "<<number<<endl;
}
Book::Book(string name,float p,int n)
{
    bookname=name;
    price=p;
    number=n;
}
int main()
{
    char name[20]="C++";
    Book book1(name,23.5,3);
    strcpy(name,"Data Structure");
    Book book2(name,28.8,7);
    book1.borrow();
    book1.display();
    book2.restore();
    book2.display();
    return 0;
}

0x02 友元函數的定義與使用


圖片.png
#include <iostream>
#include<cstring>
using namespace std;
class Stu
{   
public:
    Stu(string name,int score);
    friend void print();
    string name;
    int score;
} ;
class Tea
{   
public:
    Tea(string name,string pro);
    friend void print();
    string name;
    string pro;
} ;
Stu::Stu(string n,int s){
    name=n;
    score=s;
}
Tea::Tea(string n,string p){
    name=n;
    pro=p;
}
void print(Stu S,Tea T)
{
    cout<<"student's name:"<<S.name<<"   "<<S.score<<endl;
    cout<<"Teacher's name:"<<T.name<<"   "<<T.pro<<endl;
}

int main()
{
    char stuname[20],teaname[20],teapro[20]; 
    cout<<"請輸入學生姓名:"<<endl; 
    cin>>stuname; 
    cout<<"請輸入教師姓名:"<<endl;
    cin>>teaname;
    cout<<"請輸入教師職稱:"<<endl;  
    cin>>teapro;
    Stu student(stuname,88);
    Tea teacher(teaname,teapro);
    print(student,teacher);
    return 0;
}

0x03 立方體類的定義與使用


圖片.png
#include <iostream>
#include<cstring>
using namespace std;
class Cube
{
public:
    int l,w,h;
    Cube(int L=3,int W=2,int H=1);
    int Compute()
    {
        return(l*w*h);
    }
};
Cube::Cube(int L,int W,int H)
{
    l=L;w=W;h=H;
}
int main()
{
    int l,w,h;
    cout<<"輸入立方體的長寬高:"<<endl;
    cin>>l>>w>>h;
    Cube A(l,w,h);
    Cube B;
    cout<<A.Compute()<<endl;
    cout<<B.Compute()<<endl;
}

0x04 設計汽車類


圖片.png
#include <iostream>
#include<cstring>
using namespace std;
class Car
{
private:
        string brand;string type;int year;double price;
public:
        Car(string b,string t,int y,double p);
        Car()
        {
            brand="undefinition";
            type="undefinition";
            year=2000;
            price=0;
        }
        string GetBrand()
        {
            return brand;
        }
        string GetType()
        {
            return type;
        }
        int GetYear()
        {
            return year;
        }
        double GetPrice()
        {
            return price;
        }
};
Car::Car(string b,string t,int y,double p){
    brand=b;
    type=t;
    year=y;
    price=p;
}
int main() 
{ 
Car car1("FIAT","Palio",2007,6.5); 
cout<<car1.GetBrand (  ) <<"|"<<car1.GetType (  ) <<"|"<<car1.GetYear (  ) <<"|" <<car1.GetPrice (  ) <<endl; 
Car car2; 
cout<<car2.GetBrand (  )<<"|"<<car2.GetType (  )<<"|"<<car2.GetYear (  ) <<"|" <<car2.GetPrice (  )<<endl; 
return 0; 
}

0x05 設計學生類


圖片.png
#include <iostream>
#include<cstring>
using namespace std;
class Student
{
private:
    int age;string name;
public:
    Student(int a, string m);
    Student()
    {
        age=0;name="unnamed";
    }
    void SetMember(int a, string m)
    {
        age=a;name=m;
    }
    int Getage()
    {
        return age;
    }
    string Getname()
    {
        return name;
    }
};
Student::Student(int a,string m)
{
    age=a;name=m;
}
int main( )
{
    Student stu[3]={Student(13,"wang")} ;   /*第一個元素用帶參構造函數初始化;第二、三個元素由無參構造函數初始化,默認年齡為 0 ,姓名為 "unnamed"*/
    stu[2].SetMember(12,"zhang");           /*修改第三個元素的數據成員值*/
    cout<<stu[0].Getage( )<<","<<stu[0].Getname( )<<"\n";
    cout<<stu[1].Getage( )<<","<<stu[1].Getname( )<<"\n"; 
    cout<<stu[2].Getage( )<<","<<stu[2].Getname( )<<"\n"; /*這三句可改用一個循環*/
    return 0;
}

第四章
靜態數據成員的使用

#include <iostream>
#include <cstring>
using namespace std;

class Student
{
private:
    int age;string name;
public:
    static int count;
    Student(int m,string n)
    {
        age=m;name=n;count++;
    }
    Student()
    {
        age=0;name="unnamed";count++;
    }
    ~Student()
    {
        count--;
    }
    void Print()const
    {
        cout<<"count="<<count<<endl;
        cout<<name<<"  "<<age<<endl;
    }
};
int Student::count=0;
int main()
{
    cout<<"count="<<Student::count<<endl;
    string stuname="ZhangHong";
    Student s1,*p=new Student(23,stuname);
    s1.Print();
    p->Print();
    delete p;
    s1.Print();
    Student Stu[4];
    cout<<"count="<<Student::count<<endl;
    return 0;   
}

第五章
0x01 簡易工資管理

#include <iostream>
#include <cstring>
using namespace std;

class Employee
{   
public:
    string name;int working_years;
    Employee(string n,int y):name(n),working_years(y){}//構造函數 
    string Getname(){return name;}//名字 
    void SetWorkyears(int wy){working_years=wy;}//工作年齡 
};
class Worker:public  Employee
{ 
public:
    double pay_per_hour;int work_time;
    Worker(string n,int y,int x):Employee(n,y),work_time(x){}//構造函數 
    double count_pay(){return work_time*pay_per_hour+35*working_years;}//計算           
    void SetWorktime(int wt){work_time=wt;}//工作時長 
    void Setpay_per_hour(int x){pay_per_hour=x;}//時薪        
};
class SalesPerson:public  Employee
{       
public:
    double pay_per_hour;double saleroom;int work_time;
    SalesPerson(string n,int y,double sr,int x):Employee(n,y),saleroom(sr),work_time(x){}//構造函數 
    double count_pay(){return work_time*pay_per_hour+35*working_years+1.0*saleroom/100;}//計算
    void SetWorktime(int wt){work_time=wt;}//工作時長
    void Setpay_per_hour(int x){pay_per_hour=x;}//時薪
    void Setsalesroom(double sr){saleroom=sr;}//售出金額 
};
class Manager:public  Employee
{
public:
    Manager(string n,int y):Employee(n,y){}//構造函數
    double count_pay(){return 1000+35*working_years;}//計算
};
int main()
{
    Worker work("zhangqiang",3,200);
    work.Setpay_per_hour(50);
    cout<<"工資="<<work.count_pay()<<endl;
    work.SetWorktime(180);
    work.SetWorkyears(10);
    work.Setpay_per_hour(30);
    cout<<work.Getname()<<"  "<<work.count_pay()<<endl;
    
    SalesPerson sales("wangjun",5,300000,25);
    sales.SetWorktime(40);
    sales.Setpay_per_hour(80);
    sales.Setsalesroom(450000);
    cout<<sales.Getname()<<"  "<<sales.count_pay()<<endl;
    
    Manager mana("sunchao",20);
    cout<<mana.Getname()<<"  "<<mana.count_pay()<<endl;
    return 0;
}

0x02 長方體計算

#include <iostream>
#include <cstring>
using namespace std;

class S
{   
protected:
    float length;  float width; 
public:
    S(float l,  float w):length(l),width(w) {}//構造函數
    float area(){return length*width; }
    void disp(){cout<<area()<<" ";}
};
class V:public S
{ 
private:
    float height; 
public:
    V(float l,  float w,float h):S(l,w),height(h){}//構造函數 
    float calv(){return  length*width*height;} 
    void disp(){cout<<area()<<" ";cout<<calv()<<" ";}
};

int main()
{
    float l,w,h;
    cin>>l>>w>>h;
    V a(l,w,h);
    a.disp();
    return 0;
}

第六章
0x01 動態多態性

#include <iostream>
using namespace std;
const double PI = 3.1415 ;

class shape     
{
public: 
    virtual double volume ( ) = 0 ;//純虛函數
};

class cylinder:public shape         
{
private:
    double h , r;
public:
    cylinder  (double r , double h ):h(h) , r(r)//重載 
    {   }
    double volume() 
    {
        return h*PI*r*r ;        //圓柱的體積
    }                   
};

class sphere:public shape            
{
private:
    double r ;
public:
    sphere(double r) : r( r )//重載 
    {   }
    double volume()  
    {
        return 4*PI*r*r*r/3;     //球的體積
    }                                
};

int main() 
{
   shape *p;
   double  r,h;
   cout<<"input r & h:"<<endl;
   cin>>r>>h;
   cylinder cy(r,h);
   sphere sp(r);
   p=&cy;
   cout<<p-> volume()<<endl;            
   p=&sp;
   cout<<p-> volume()<<endl; 
   return 0;
}

0x02 矩陣類運算符重載

#include <iostream>
#include <stdlib.h>
using namespace std;

class Matrix    
{
private:
    int row,col,*m;
public: 
    Matrix(int r,int c):row(r),col(c)//重載 
    {
        cout<<"請輸入該矩陣元素:"<<endl;
        m = new int[row*col];
        for(int i=0;i<row*col;i++)
        {
            cin >> m[i];
        }
    }
    Matrix():row(3),col(3)//重載 
    {
        m = new int[9];
    }
    friend Matrix operator + (const Matrix &a, const Matrix &b)//加 
    {
        Matrix tempt;
        if(a.row!=b.row||a.col!=b.col)
        {
            cout<<"program terminated!"<<endl;
            system("pause");
        }
        else
        {
            for(int i=0;i<a.row*a.col;i++)
            {
                tempt.m[i]=a.m[i]+b.m[i];
            }
            return tempt;
        } 
    }
    Matrix & operator = (const Matrix &s)//賦值 
    {
        m = new int[s.row*s.col];
        for(int i=0;i<s.row*s.col;i++)
        {
            m[i]=s.m[i];
        }
        return *this ;
    }
    ~Matrix()//析構 
    {
        delete []m;
    }
    void disp();
};

void Matrix::disp()
{
    for(int i=0;i<row;i++)
    {
        cout<<'\t';
        for(int j=0;j<col;j++)
            cout<<*(m+i*col+j)<<'\t';
        cout<<endl;
    }
}

int main()
{
    int row_a,col_a,row_b,col_b;
    cout<<"請輸入am矩陣的行數和列數:"<<endl;
    cin>>row_a>>col_a;
    Matrix am(row_a,col_a);
    cout<<"請輸入bm矩陣的行數和列數:"<<endl;
    cin>>row_b>>col_b;
    Matrix bm(row_b,col_b),cm;
    cout<<"am:"<<endl;
    am.disp();
    cout<<"bm:"<<endl;
    bm.disp();
    cm=am+bm;
    cout<<"cm=am+bm:"<<endl;
    cm.disp();
    am=bm;
    cout<<"am=bm:"<<endl;
    am.disp();
    return 0;
}

Part 6/6 編程練習

第2章 對C的改進及擴展
基本格式

#include <iostream>
using namespace std;

int main( )
{    
    return 0;
}

bool類型

bool Larger(int x , int y)    
{    
     if ( x > y )              
        return true;
     return false;               
}
int main( )
{    
    int x , y;   
    cin >> x >> y;                  
    bool t = Larger(x , y);  
    // false為 0,true為 1 
    cout << boolalpha << t << endl << noboolalpha << t << endl;
    return 0;
}

名字空間

namespace one               
{   
    int M = 200;      
    int f = -10;           
}                          
namespace two             
{             
    int f = -100 ;        
}                         
using namespace one ;   

int main( )
{    
    cout << M << endl; 
    cout << f << endl;   
    using two::f;   
    f = 123;    
    cout << f << endl; 
    return 0;
}

string類型應用,insert,replace,substr,find,erase函數

int main( )
{   
    string  s1, s2, s3;
    cin >> s1; // 讀入不帶空格的字符串,例如 "ABC" 
    cout << s1 << endl; 
    getline(cin,s1); // 讀入帶空格的字符串,例如 " A BC" 
    cout << s1 << endl; 
    s2 = "Student";     
    s3 = s2;  
    cout << s3 << endl;
    string s4 (8, 'A'); // "AAAAAAAA"  
    cout << s4 << endl;                     
    s2 = s3 + '&' + s4 ; // "Student&AAAAAAAA"
    cout << s2 << endl;
    
    s3.insert(7 , "&Teacher");  // "Student&Teacher"
    cout << s3 << endl;
    s3.replace(2 , 4 , "ar");  // "uden" 替換為 "ar","Start&Teacher" 
    cout << s3 << endl;
    s1 = s3.substr(6 , 7);  // 從 "Start&Teacher"中獲取 "Teacher"
    cout << s1 << endl;
    int pos = s3.find(s1);  // s1在s3中第 6 位 
    cout << pos << endl;
    s3.erase(5 , 8);    // 從 "Start&Teacher"中刪除 "&Teacher"
    cout << s3 << endl;
    bool f = s1 > s4;   // true 
    cout << boolalpha << f << endl;
    return 0;
}

全局變量與局部變量

int A = 20; 
int main( )
{   
    int a[3] = {10 , 20 , 30};        
    int A = 0; 
    // 局部變量 A=60           
    for (int i = 0 ; i < 3 ; i++){
        A+=a[i];
    }    
    ::A += A;    // 全局變量 ::A=80    
    cout << A << endl << ::A << endl;
    return 0;
}     

形參帶默認參數值的函數

void Fun( int i , int j  , int k=10 ){
    cout << i << " "<< j << " " << k << endl;
}
int main( )
{   
//  Fun ( 20 ); 報錯
    Fun ( 20 , 30 ); // k默認為 10  
    Fun ( 20 , 30 , 40 ); // k替換為 40 
    return 0;
} 

重載函數

int square ( int x ){                      
    cout << x * x << endl;  
}
float square ( float x ){                       
    cout << x * x << endl; 
}
double square ( double x ){                      
    cout << x * x << endl; 
}
int main( )
{   
    square ( 11 ); 
    square ( 1.1f );
    square ( 1.11 );
    return 0;
}

引用的聲明及訪問

int x = 5 , y = 10 ;
int &r = x ;   
     
void print( ){    
     cout << "x= " << x << " y= " << y << " r= " << r << endl ;
     cout << "Address of x " << &x << endl;         
     cout << "Address of y " << &y << endl;         
     cout << "Address of r " << &r << endl;         
}
int main( )
{   
    print (); // x=5 y=10 r=5
    y = 100;                      
    x = y - 10;                   
    print (); // x=90 y=100 r=90
    return 0;
}

引用作參,修改實際參數的值

void swap ( int &x , int &y ){                   
    int t = x ;   //t=3 
    x = y ;       //x=5              
    y = t ;       //y=3                     
}
int main( )
{   
    int a = 3 , b = 5 ;
    swap ( a , b ) ;                              
    cout << "a= " << a << " b= " << b << endl; 
    return 0;
}

三種參數的使用

int Fun (const int &x , int &y , int z){   
//  x++ ; 報錯,x不可修改 
    y++ ;                           
    z++ ;           
    return y ;        
}
int main( )
{   
    int a = 1, b = 2, c = 3, d = 0;
    d = Fun ( a , b , c ) ;    // a不變,b=2+1,c不變,d=b
    cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl;
    return 0;
}

異常處理過程和方法

double divide(int x,int y){   
    // 如果分母為零,拋出異常 
    if ( y == 0 ){
        throw 2.333; 
    } 
    return x*1.0 / y;
}
int main( )
{   
    int a = 9, b = 5, c = 0;
    // 檢查是否出現異常
    try{   
        cout << "a/b = " << divide (a , b) << endl;
        cout << "b/a = " << divide (b , a) << endl;
        cout << "a/c = " << divide (a , c) << endl;// 失敗,不再try 
        cout << "c/b = " << divide (c , b) << endl;// 沒有執行 
    }
    // catch到小數2.333 
    catch ( double ){   
        cout << "有分母為零的情況" << endl; 
    }
    return 0;
}

第3章 類與對象1
類對象數據成員

class CDate{
public:
    int year;
    int month;
    int day;
};
int main( )
{   
    CDate date1;                      
    CDate date2;
    int age(0);// int age=0
    date1.year = 2019; date1.month = 3; date1.day = 9;
    date2.year = 1999; date2.month = 3; date2.day = 9;
    age = date1.year - date2.year;             
    cout << "He is " << age << " years old" << endl;
    cout << date2.year << " - "<< date2.month << " - " << date2.day << endl;
    cout << "date1 occupies " << sizeof(date1) << " bytes."; // 3 * 4 =12
    return 0;
}

this 指針

class CDate{
private:
    int Year, Month, Day;
public:
    void SetDate(int y,int m,int d){   
    Year = y;
    Month = m;
    Day = d; 
    }   
    void  Display( ){
    cout << "this 指針是: "<< this <<endl;                   
    cout << "Year地址: "  << &this -> Year << endl;    
    cout << "Month地址: "<< &this -> Month << endl;
    cout << "Day地址: "<< &this -> Day << endl;
    }
};
int main( )
{   
    CDate a ;
    a.SetDate (2019, 3, 9);    
    cout << "a地址: " << &a << endl;
    a.Display();
    return 0;
}

兩種方式創建對象

class CDate{
    int Year, Month, Day;
public:
    CDate(int y=2000, int m=1, int d=22 ){ 
        Year = y; Month = m; Day = d; 
    }
    void  Display( ){
        cout << this->Year << " - "<< this->Month << " - " << this->Day << endl;                   
    }
};  
int main( )
{   
    CDate day1 (2019,3);// 初始化 day1
    CDate day2 = day1;  // 用day1初始化 day2
    day1.Display();
    day2.Display();
    return 0;
}

構造與析構順序

class CDate
{   
    int year, month, day ;   
public:                  
    // 構造函數              
    CDate(int y=2000, int m=1, int d=1):year(y), month (m), day(d){
        cout << "構造成功" << endl;
    }      
    // 拷貝構造函數
    CDate(const CDate &x){
        year = x.year; month = x.month; day = x.day + 1;
        cout << "拷貝構造成功" << endl;
    }          
    void  Display ( ){
        cout<< year << "-" << month << "-" << day << endl;
    }  
    // 析構函數
    ~CDate(){
        cout << "析構成功" << endl; 
    }                  
};
CDate f (CDate day1){   
    CDate day2 (day1);   
    return day2;             
}                              
int main( )
{   
    CDate day1 (2019,3,9) ;      // 構造 day1 
    CDate day3;                  // 構造 day3 
    CDate day2 (day1) ;          // 拷貝構造 day2, 9+1=10
    CDate day4 = day2;           // 拷貝構造 day4, 10+1=11
    day3 = day2;                 // 拷貝構造 day3 
    day3 = f (day2);             // 拷貝構造 day3, 11+1=12
    // f 里的 day2,day1依次析構
    day3.Display( );            //2019-3-12
    // day4,day3,day2,day1依次析構 
    return 0;
}

類對象數組,初始化及訪問

class CDate{   
    int year, month, day;    
public :                                
    CDate(int y=2000, int m=1, int d=1): year(y), month (m), day(d) 
    {  }     
    void  Display ( ){
        cout<< year << "-" << month << "-" << day << endl;
    } 
};                         
int main( )
{   
    CDate x[3]={ CDate(2019,3,8), CDate(2019,3,11) };
    for(int i=0; i< 3;  i++){
        x[i].Display( );
    } 
    return 0;
}

第4章 類與對象2
包含類1

class A{
public:
    A( ){
        cout << "創建A" << endl; 
    }
    ~A( ){
        cout << "析構A" << endl; 
    }
};
class B{
public:
    B( ){
        cout << "創建B" << endl; 
    }
    ~B( ){
        cout << "析構B" << endl; 
    }
private:
    A a;// B類包含了A類
};
int main( )
{
    B  b;
    return 0;
}   

包含類2

class CDate{   
    int year, month, day;   
public :                                
    CDate(int y, int m, int d):year(y),month (m),day(d) {       
        cout << "CDate 構造成功" << endl;
    }
    void  Display( ){   
        cout<< year << "-" << month << "-" << day << endl;
    }
    ~CDate(){
        cout << "CDate 析構成功" << endl;
    }
};

class Croster{
private:
    string name;
    CDate birthday;// Croster類包含了CDate類
public:
    Croster(string na, int y, int m, int d): birthday( y, m, d){
        cout << "Croster 構造成功" << endl;
        name = na;
    }
    void Display(){
        cout << name << " : ";
        birthday.Display();
    }
    ~Croster(){
        cout << "Croster 析構成功" << endl;
    }
};
int main()
{
    Croster stuA("趙焱", 2001, 1 ,29 );
    stuA.Display();
    return 0;
}

靜態數據成員1

class Croster{
public:
    static int Count;
private:
    string name; int Math; int English;
public:
    Croster(string na="undefine", int m= 100, int e= 100): name(na), Math(m), English(e){ 
        cout << "歡迎新同學!" << endl ;
        Count -- ;
    }
};
int Croster :: Count = 100;// 初始化靜態數據成員
int main()
{
    cout << "人數 : " << Croster::Count << endl;
    Croster list[3];
    cout << "人數 : " << list[1].Count << endl;
    Croster A;
    cout << "人數 : " << A.Count << endl;
    return 0;
}

靜態數據成員2

class Croster{
public:
    static int Count;
private:
    string name; int Math; static int Sum;
public:
    Croster(string na= "undefine", int m= 100): name(na), Math(m){ 
        cout << "歡迎新同學!" << endl ;
        Count -- ;
        Sum += Math;
    }
    static void Display(){
    //  cout << "name: " << name << endl; 報錯 
        cout << "Sum = " << Sum << ", ";
        if ( Count == 100 ){
            cout << "Average = 0 " << endl;
        } 
        else{
            cout << "Average = " << Sum* 1.0/ (100-Count) << endl;
        } 
    }
};
int Croster :: Count = 100;  
int Croster :: Sum;// 默認初始值為0    
int main()
{
    Croster::Display();
    Croster list[3] ={ Croster("趙焱",95), Croster("錢朵", 90), Croster("孫力", 92) };
    list[2].Display();
    return 0;
}

靜態數據成員3

class Croster{
private:
    string name; 
    double GPA, Math;  
    static const double Score  ;                   
public:
    Croster(string na= "undefine", double m= 100){   
        name = na; Math = m ;
    } 
    double GetGPA(){
        GPA = Math/10 - Score;
        return GPA;
    }
    void Display(){
        cout << name << "的成績為:" << Math << ", " << "績點為:" << GetGPA() << endl;
    }
};
const double Croster::Score = 5.00;  
int main()
{
    Croster A("趙焱", 93.5);
    A.Display();
    return 0;
}

第5章 繼承與派生
單繼承

#include <iostream>
using namespace std;

class Base
{
private:
    int b1;
protected:
    int b2;
public:
    void set(int m, int n){
        b1 = m;
        b2 = n;
    }
    void show( ){
        cout << "b1 = " << b1 << endl;
        cout << "b2 = " << b2 << endl;
    }
};
class Derived: public Base// 公有派生類
{
private:
    int d;
public:
    void set2(int m, int n, int l){
        set(m,n);
        d = l;
    }
    void show2( ){
        show( );
        cout << "d = " << d << endl;
    }
};
int main( )
{
    Derived obj;
    obj.set2(30, 40, 50);
    obj.show( );
    obj.show2( );
    return 0;
}

多重繼承

#include <iostream>
using namespace std;

class BaseA
{
private: int a1;
protected: int a2;
public: int a3;
    void setA(int x, int y, int z){
        a1 = x; a2 = y; a3 = z;
    }
    void showA( ){
        cout << " a1 = " << a1 << ", a2 = " << a2 << ", a3 = " << a3 << endl;
    }
};

class BaseB
{
private: int b1;
protected: int b2;
public: int b3;
    void setB(int x, int y, int z){
        b1 = x; b2 = y; b3 = z;
    }
    void showB( ){
        cout << " b1 = " << b1 << ", b2 = " << b2 << ", b3 = " << b3 << endl;
    }
};

class BaseC
{
private: int c1;
protected: int c2;
public: int c3;
    void setC(int x, int y, int z){
        c1 = x; c2 = y; c3 = z;
    }
    void showC( ){
        cout << " c1 = " << c1 << ", c2 = " << c2 << ", c3 = " << c3 << endl;
    }
};

class Derived: public BaseA, protected BaseB, private BaseC
{
private: int d1;
protected: int d2;
public: int d3;
    void setD(int x, int y, int z){
        d1 = x; d2 = y; d3 = z;
    }
    void showD( ){
        cout << " d1 = " << d1 << ", d2 = " << d2 << ", d3 = " << d3 << endl;
    }
    void setall(int x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10, int x11 ){
        setA(x0, x1, x2);
        setB(x3, x4, x5);
        setC(x6, x7, x8);
        setD(x9, x10, x11);
    }
    void showall( ){
        showA( ); showB( ); showC( ); showD( );
    }
};
int main( )
{
    Derived obj;
    obj.setall(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120);
    obj.showA( );//       showA( )為 public成員,可以通過 obj訪問
//  obj.showB( );         showB( )為 protected成員,無法通過 obj訪問
//  obj.showC( );         showC( )為 private成員,無法通過 obj訪問
    obj.showD( );           
    obj.showall( );
    return 0;
}

構造,析構

#include <iostream>
using namespace std;

class Base//基類 
{
public:
    Base( ){cout << "構造A"<<endl;  }
    ~Base( ){cout << "析構A"<<endl; }
};
class Derived: public Base//派生類             
{                           
public:
    Derived( ){cout << "構造B"<<endl; }
    ~Derived( ){cout << "析構B"<<endl;  }
};
int main( )
{
    Derived obj;
    return 0;
}

多重繼承下構造,析構

#include <iostream>
using namespace std;

class Grand
{
public:
    int a;
    Grand(int n): a(n)// a=1 
    {cout << "構造Grand, a = " << a << endl;}
    ~Grand( ){cout << "析構Grand" << endl;}// 析構 
};
class Father: public Grand
{
public:
    int b;
    Father(int n1,int n2): Grand(n1), b(n2)// Grand(1), b=2 
    {cout << "構造Father, b = " << b << endl;};
    ~Father( ){cout << "析構Father" << endl;}// 析構 
};
class Mother
{
public:
    int c;
    Mother(int n): c(n)// c=2
    {cout << "構造Mother, c = " << c << endl;}
    ~Mother( ){cout << "析構Mother" << endl;}// 析構 
};
class Son: public Father, public Mother
{
public:
    int d;
    Son(int n1, int n2, int n3, int n4): Father(n1, n2), Mother(n3), d(n4)// Father(1,2), Mother(3), d=4 
    {cout << "構造Son, d = " << d << endl;}
    ~Son( ){cout << "析構Son" << endl;}// 析構 
};
int main( )
{
    Son s(1,2,3,4);
    return 0;
}

派生類,基類有同名成員

#include <iostream>
using namespace std;

class Base
{
public:
    int a;
    Base(int x){
        a = x;
    }
    void Print1( ){
        cout << "Base::a = " << a << endl; 
    }
};
class Derived: public Base// 派生類 
{
public:
    int a;
    Derived(int x, int y): Base(x){
        a = y;              
        Base::a *= 2 ;      
    }
    void Print2( ){
        Base::Print1( );     
        cout << "Derived::a = " << a << endl;
    }
};

void f1(Base &obj)    {obj.Print1( );}
void f2(Derived &obj)    {obj.Print2( );}

int main( )
{
    Derived d(200,300) ;  
    d.Print2( );             // 輸出1, 2行 
    d.a = 400;             
    d.Base::a = 500;        
    d.Base::Print1( ) ;      // 輸出3行 
    Base *pb; 
    pb = &d;                
    pb -> Print1( );         // 輸出4行 
    f1(d);                   // 輸出5行 
    Derived *pd;
    pd = &d;                
    pd -> Print2( );         // 輸出6,7行 
    f2(d);                   // 輸出8,9行 
    return 0;
}

多重繼承中,直接基類有同名成員

class Base1{
public:
    int a;
    Base1(int x):a(x){
        cout << "Base1 a = " << a << endl;
    }
};
class Base2{
public:
    int a;
    Base2(int x):a(x){
        cout << "Base2 a = " << a << endl;
    }
};
class Derived: public Base1, public Base2{
public:          
    Derived(int x,int y):Base1(x),Base2(y){
        Base1::a *= 2 ; 
        Base2::a *= 2 ;         
        cout << "Derived from Base1::a = "<<Base1::a << endl;               
        cout << "Derived from Base2::a = "<<Base2::a << endl;               
    }
};
int main( ){
    Derived obj(10, 20);
    return 0;
}

多層繼承中,有共同的祖先基類

// 共同的祖先基類
class Base{
public:
    int a;
    Base(int x): a(x){ 
        cout << "基類 a = " << a << endl; 
    }
    ~Base( ){
        cout << "析構基類" << endl;
    }
};
// 派生一 
class Base1: public Base{
public:
    int b;
    // Base(20), c(10) 
    Base1(int x, int y): Base(y), b(x){
        cout << "派生一 a = " << a << endl;
        cout << "派生一 b = " << b << endl;
    }
    ~Base1( ){
        cout << "析構派生一" << endl; 
    }
};
// 派生二 
class Base2: public Base{ 
public:
    int c;
    // Base(40), c(20) 
    Base2(int x, int y): Base(y), c(x){ 
        cout << "派生二 a = " << a << endl;
        cout << "派生二 c = " << c << endl;
    }
    ~Base2( ){
        cout << "析構派生二" << endl; 
    }
};
class Derived: public Base1, public Base2{
public:
    // Base1(10, 20), Base2(20, 40)
    Derived(int x, int y): Base1(x, y), Base2(2*x, 2*y){
        cout << "Derived from Base1::a = "<< Base1::a << endl;                  
        cout << "Derived from Base2::a = "<< Base2::a << endl;                  
        cout << "Derived from Base1 b = "<< b << endl;                  
        cout << "Derived from Base2 c = "<< c << endl;                  
    }
    ~Derived( ){
        cout << "析構Derived" << endl;
    }
};
int main( ){   
    Derived obj(10, 20);
    return 0;
}

虛基類

class Base{
public:
    int a;
    Base(int x): a(x){ 
        cout << "Base a = " << a << endl; 
    }
};
// 虛基類一 
class Base1: public virtual Base{
public:
    int b;
    Base1(int x, int y): Base(y), b(x){
        cout << "虛基類一 a = " << a << endl;
        cout << "虛基類一 b = " << b << endl;
    }
};
// 虛基類二 
class Base2: public virtual Base{ 
public:
    int c;
    Base2(int x, int y): Base(y), c(x){ 
        cout << "虛基類二 a = " << a << endl;
        cout << "虛基類二 c = " << c << endl;
    }
};
class Derived: public Base1, public Base2{
public:
    // Base1(10, 20), Base2(20, 40), Base(30)
    Derived(int x, int y): Base1(x, y), Base2(2*x, 2*y), Base(3*x){
        cout << "a = " << a << endl << "b = " << b << endl << "c = " << c << endl;
        cout << "Base::a = " << Base::a << endl << "Base1::a = " << Base1::a << endl << "Base2::a = " << Base2::a << endl;
    }
};
int main( ){
    Derived obj(10, 20);
    return 0;
}

賦值兼容規則

class Base{
public:
    int b;
    Base(int x): b(x){  }
    int getb( ){ return b; }
};
class Derived: public Base{
public:
    int d;
    Derived(int x, int y): Base(x), d(y){  }
    int getd( ){ return d; }
};
int  main( ){
    Base B(11);
    Derived D(22, 33);
    // 第一種賦值兼容
    B = D;
    // 第二種賦值兼容
    Base *B1 = &D;  
    // 第三種賦值兼容
    Derived *D1 = &D;
    Base *B2 = D1;
    // 第四種賦值兼容
    Base &B3 = D;
    cout << "B.getb( ) = " << B.getb( ) << endl;
    cout << "B1->getb( ) = " << B1->getb( ) << endl;
    cout << "B2->getb( ) = " << B2->getb( ) << endl;
    cout << "B3.getb( ) = " << B3.getb( ) << endl;
    return 0;
}

第6章 多態性
靜態多態性

class Student{  
    string name;
    int no;
public:
    Student():name("同學"),no(0){  
    }                                  
    Student(string s, int n): name(s), no(n){  
    }
    void  print(){   
        cout << name << "  " << no << endl; 
    }                       
    void  print(int x){
        cout << name << "  B" << x << "  "<< no << endl;             
    }            
};
int  main( ){
    Student  s1;   
    s1.print ( );              
    Student  s2("學生", 18);                  
    s2.print ( );             
    s2.print (2019);  
    return 0;
}

重載運算符 "+"

class Complex{
private:
    float  real, imag; 
public:
    Complex (float r = 0, float i = 0):real(r),imag(i){ 
    } 
    void print ( ){ 
        cout << real << "+" << imag << "i" <<endl;                            
    } 
    Complex operator + (Complex &a){    
        Complex t;
        t.real = real + a.real ; 
        t.imag = imag + a.imag ;     
        return t;
    }
    Complex operator + (float x){
        return Complex (real+x, imag) ;
    }            
};

int  main( ){
    Complex c1 (1.5 , 2.5), c2(5 , 10), c3;
    cout << "c1 = " ;  c1.print( );
    cout << "c2 = " ;  c2.print( );
    c3 = c1 + c2 ; 
    cout << "c3 = c1+c2 = ";  c3.print( );
    c3 = c3 + 3.5 ; 
    cout << "c3 + 3.5 = ";  c3.print( ); 
    return 0;
}

重載運算符 "="

#include <iostream>
#include <cstring>
using namespace std;

class CMessage{
private:
    char* p;                              
public:
    CMessage(char* text = "ABC"){
        // 申請動態空間
        p = new char[strlen(text) + 1]; 
        strcpy(p, text);
    }
    void show(){
        cout << p <<endl;
    }
    // 賦值運算符 
    CMessage & operator = (CMessage &s){
        p = new char[strlen(s.p) + 1];
        strcpy(p, s.p);
        return *this ;
    }
};  
int  main( ){
    CMessage Mes1("愛我中華");
    CMessage Mes2;   
    Mes1.show(); Mes2.show();
    Mes2 = Mes1;
    Mes1.show(); Mes2.show();
    return 0;
}

重載運算符 “[ ]"

class Array{
    int  *m, num;                                   
public:
    Array(int n):num(n){      
        m = new int [num];
        for (int i = 0; i < num; i++){
            m[i] = (i+1)*10; 
        }
    }          
    // 調用運算符
    int & operator [] (int r){
        if(r>=0 && r<num){
            return *(m+r);
        }
        return *m;
    } 
    void show( ){
        for (int i = 0; i < num; i++){
            cout << "  " << m[i];
        }      
        cout << endl;
    }              
};   
int  main( ){
    Array  a(5); a.show( );  
    // *(a+2) = 800      
    a[2] = 800; a.show( ); 
    // *a = -100
    a[23] = -100; a.show( ); 
    return 0;
}

重載運算符 ">>","<<"

class Complex{
    float real, imag;
public:
    Complex (float r=0, float i=0): real(r),imag(i){   
    }
    friend istream & operator >> (istream &i, Complex &a){
        i >> a.real >> a.imag ; 
        return i;
    }
    friend ostream & operator << (ostream &o, Complex &a){
        o << a.real << "+" << a.imag << "i" << endl;   
        return o;
    }   
};
int  main( ){
    Complex c1, c2;
    cout << "input c1, c2:" << endl;
    cin >> c1 >> c2;
    cout << "c1 = " << c1 << "c2 = " << c2;  
    return 0;
} 

重載運算符 “++”,“--”

class Complex{
    float real, imag;
public:
    Complex operator -- ( ){
        --real; --imag;                 
        return *this;
    }
    Complex operator ++ ( ){
        ++real; ++imag;                 
        return *this;
    }
    Complex operator -- (int){
        Complex t(*this);     
        real--; imag--;
        return t; 
    }
    Complex operator ++ (int){
        Complex t(*this);     
        real++; imag++;
        return t;       
    }
    friend istream & operator >> (istream &i, Complex &a){
        i >> a.real >> a.imag ; 
        return i;
    }
    friend ostream & operator << (ostream &o, Complex &a){
        o << a.real << "+" << a.imag << "i";   
        return o;
    }  
};
int  main( ){
    Complex c1, c2;
    cout << "input c1, c2:" << endl;
    cin >> c1 >> c2;
    cout << "c1 = " << c1 << "c2 = " << c2;  
    c1++; cout << "c1++ = " << c1 << endl;  
    ++c1; cout << "++c1 = " << c1 << endl;  
    c2++; cout << "c2++ = " << c2 << endl;  
    ++c2; cout << "++c2 = " << c2 << endl;  
    return 0;
}

虛函數的 Print()

class Base{
public:
    int a;
    Base(int x):a(x){
    }
    virtual void Print( ){
        cout << "Base::a = " << a << endl; 
    }
};
class Derived: public Base{
public:
    int a;
    Derived(int x, int y): Base(x),a(y){           
        Base::a *= 2 ;      
    }
    void Print( ){
        Base::Print( );     
        cout << "Derived::a = " << a << endl;
    }
};
void f1(Base &x){
    x.Print( );
}
void f2(Derived &x){
    x.Print( ); 
}
int  main( ){               
    Derived d(200,300) ;  // Base(200), d.a(300)
    d.Print( );         
    d.a = 400;            // d.a(400)
    d.Base::a = 500;      // Base(500)
    d.Base::Print( ) ;   
    Base b(8);            // b.a(8)
    Base *pb;               
    pb = &b;              // pb->a=8  
    pb -> Print( );       
    pb = &d;              // pb-> Base::a=500, pb-> a=400  
    pb -> Print( );     
    f1(b);             
    f1(d);              
    Derived *pd;
    pd = &d;              // pd-> Base::a=500, pd-> a=400
    pd -> Print( );     
    f2(d);              
    return 0;
}

虛函數的析構

class A{
public:
    virtual  ~A( ){
        cout << "析構A"<< endl;
    } 
};
class B: public A{
public:
    virtual ~B ( ){
        cout << "析構B" << endl;
    }              
};
int  main( ){
    A *a = new B();  
    delete a ;            
    return 0;
}

虛函數的同名覆蓋

class base{
public: 
    // 虛函數
    virtual void f1( ){
        cout << "f1() of base "<< endl ;     
    } 
    // 虛函數 
    virtual void f2( ){
        cout << "f2() of base "<< endl ;     
    } 
}; 
class derive: public base{
 public:
    void f1( ){
        cout << "f1() of derive "<< endl;       
    } 
    void f2 (int x){ 
        cout << "f2() of derive "<< endl;       
    } 
    // 普通函數
    void f3(){ 
        cout << "f3() of derive "<< endl;       
    } 
};
int main(){
    derive x;
    x.f1 ( );     
    x.base::f2( );
    x.f2 (1);     
    x.f3 ( );   
    return 0;
}

純虛函數

class Point{
public:
    // 純虛函數
    virtual void Draw () = 0 ; 
};
class Line:public Point{
public:
    void Draw ( ){
        cout << "Line::Draw is called"<<endl ;
    }           
 };
class Circle:public Point{
public:
    void Draw ( ){
        cout << "Circle::Draw is called"<<endl ;
    }           
};
void Function(Point *p){ 
    p-> Draw( );      
}
int main(){
//  Point p; 報錯 
    Line L; Function(&L);
    Circle C; Function(&C);     
    return 0;
}

純虛函數的抽象類

class Shape{
public: 
    virtual double area( )= 0 ;
};
class Triangle: public Shape{
    double base, hight;
public:
    Triangle (double b, double h):base(b), hight(h){   
    }
    double area(){
        return 1/2*base*hight;     
    }               
};
class Rectangle:public Shape{
    double hight, width;
public:
    Rectangle(double h, double w):hight(h), width(w){   
    }
    double area(){
        return hight*width ;         
    }                   
};
class Circle:public Shape{
    double radius;
public:
    Circle(double r):radius(r){  
    }
    double area(){
        return 3.14*radius*radius;    
    }                                
};
int main(){
    Shape *p[3];                    
    p[0] = new Rectangle (2.5, 10.0); 
    p[1] = new Rectangle(15, 22);  
    p[2] = new Circle(3.0);         
    cout << "三角形面積: " << p[0]->area( ) << endl ;    
    cout << "長方形面積: " << p[1]->area( ) << endl ;
    cout << "圓形面積: " << p[2]->area( ) << endl;   
    return 0;
}

第7章 模板
函數模板

// 函數模板
template <class T>                         
T Max(T x, T y){   
    return x>y ? x:y;
}                                         
int main(){
    cout << Max(2, 8) << endl;            
    cout << Max(2.5, 8.5) << endl;         
//  cout << Max(2, 8.5) << endl; 報錯 
    cout << Max <int>(2, 8.5) << endl;      
    cout << Max <double>(2, 8.5) << endl;  
    return 0;
}

模板函數的重載

#include <iostream>
#include <cstring>
using namespace std;

template <class T>
T Max(T x, T y){   
    return x>y ? x:y;
}
char* Max(char* x, char* y){    
    return (strcmp(x,y)>0 ? x:y);
}                                      
int main(){
    cout << Max('2', '8') << endl;        
    cout << Max("gorilla", "star") << endl;  
    return 0;
}   

類模板

template <class A, class B>
void sum(A a1, B a2){
    cout << (a1+a2);
}                                 
int main(){
    string a = "abc";
    string b = "cba";
    sum(a,b);
    return 0;
}

第8章 文件及輸入輸出
cin,cin.get( ),cin.getline( ),getline( )

int main() { 
    char s1[80], s2[80], s3[80];
    string str1, str2;
    cout << "Enter sentence A: " << endl;       
    cin >> s1;                                                   
    cin.get (s2, 80);
    cout << "Enter sentence B: " << endl;         
    cin >> s1;                                                   
    cin.getline(s3, 80);   
    cout << "Enter sentence C: " << endl;                     
    cin >> str1;
    getline (cin, str2);
    cout << "cin: " << s1 << endl;         
    cout << "cin.get: " << s2 << endl;     
    cout << "cin: " << s1 << endl;                                                   
    cout << "cin.getline: " << s3 << endl; 
    cout << "cin: " << str1 << endl;              
    cout << "getline: " << str2 << endl;           
    return 0;
}

setf( ),unsetf( )

int main( ){ 
    cout.setf ( ios::showpos );  
    cout.setf ( ios::scientific ); //科學計數法
    cout << 123 << " " << 123234.5 << endl;
    cout.unsetf ( ios::showpos );          
    cout << 123 << " " << 123234.5 << endl;  
    return 0;
}

操縱函數 setw

#include<iostream>
#include<iomanip>
using namespace std;

int main(){ 
    int i = 6789, j = 1234, k = -10;
    cout << setw(6) << i << j << k << endl;
    cout << setw(6) << i << setw(8) << j << setw(10) << k << endl;
    return 0;
}

輸出控制符函數 setup

#include <iostream>
#include <iomanip>
using namespace std;

ostream & setup (ostream &s){
    s.setf ( ios::left );  //左對齊
    s << setw(10) << setfill('$'); //域寬10,空白處用$填充
    return s;
}
int main(){ 
    cout << 10 << "Hello!" << endl;
    // 10 域寬2,"Hello!" 域寬6 
    cout << setup << 10 << "Hello!" << endl;
    cout << setup << 10 << setup  << "Hello!" << endl; 
    return 0;
}

“>>”,“<<” 文本操作

#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;

void CreateFile(){   
    ofstream x ( "d:\\f1.txt" );              
    x << 10 << " " << 3.1415926;       
    x << "~ This is a short text file ~"; 
    x.close();                      
}
void ReadFile(){   
    int i; double d; string str;
    ifstream y ( "d:\\f1.txt" );           
    y >> i >> d ;                   
    cout << i << " " << d <<endl;            
    getline(y, str);                 
    cout << str << endl;                
    y.close();                        
} 
int main(  ){   
    CreateFile();           
    ReadFile();         
    return 0;
}

get(),put() 文本操作

int main ( ){ 
    //打開文本 
    ifstream x ( "d:\\abc.txt" );   
    ofstream y ( "d:\\xyz.txt" );  
    char c;
    //復制和輸出
    while(x.get(c)){
        y.put(c);               
        cout.put(c);
    }
    x. close( );                    
    y. close( );                    
    return 0;
}

read(),write() 文本操作

void CreateBiFile( ){
    ofstream x ( "d:\\test.txt" );         
    double num = 3.1415926;          
    string str = "abcDEFlmn";
    char s[100];
    strcpy (s, str.c_str( ));  
    
    x.write ((const char *)&num, sizeof(double)); //寫入數字 100 
    x.write (s, strlen(s)); //寫入字符串 "abc" 
    x.close ( ) ;                   
}
void ReadBiFile(  ) 
{ 
    ifstream y( "d:\\test.txt" );         
    double num;
    char s[100] = "";    
                
    y.read(( char *)&num, sizeof(double)); //讀取數字 
    y.read(s, 100 ); //讀取字符串 
    cout << num << ' ' << s;                 
    y.close();                     
}
int main(){  
    CreateBiFile ( );
    ReadBiFile ( ); 
    return 0;
}

讀寫示例

int main(){   
    // 可讀可寫
    fstream x("d:\\test.txt", ios::in|ios::out); 
    long i, j;
    char c1, c2;
    // 將前5個字符順序顛倒 
    for(i=0,j=4; i<j; i++,j--){               
    // seekg()是輸入流的操作,g是get縮寫                             
        x.seekg(i, ios::beg); x.get(c1);
        x.seekg(j, ios::beg); x.get(c2);
        x.seekg(j, ios::beg); x.put(c1);
        x.seekg(i, ios::beg); x.put(c2);
    }
    x.close();                     
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。