C++初級學習的一些實例代碼

C++初級學習的一些實例代碼<譚浩強版C++>

參考文檔:C++學習總結

<>

<>

<枚舉類型與switch語句>

#include <iostream>
using namespace std;

void main()
{
    enum {red,blue,yellow,black};
    int se;
    cin>>se;
    switch(se)
    {
    case red:cout<<"red.";break;
    case blue:cout<<"blue.";break;
    case yellow:cout<<"yellow.";break;
    case black:cout<<"black.";break;
    default :cout<<"have no ideal.";break;
    }
    system("pause");
}

<延時程序>

void main()
{
    cout<<"Enter the delay time,in seconds:";
    float secs;
    cin>>secs;
    clock_t delay=secs*CLOCKS_PER_SEC;//CLOCKS_PER_SEC等於每秒鐘包含的系統時間單位數
    cout<<"starting\a\n";
    clock_t start=clock();                    //clock_t作爲clock()返回類型,根據系統不同,可能是long、usigned long等
    while(clock()-start<delay)
        ;
    cout<<"done!\a\n";
    system("pause");
}

<類模板——int/float/char型比較>

#include <iostream>
using namespace std;

template <class numtype>
class Compare
{
public:
    Compare(numtype a,numtype b){x=a;y=b;}
    numtype max(){return (x>y)?x:y;}
    numtype min(){return (x<y)?x:y;}
private:
    numtype x,y;
};

void main()

{

    Compare <int>cmp1(4,5);//使用類模板時,對象的定義方式與一般對象略有不同

   Compare <double>cmp2(23,56,43.72);

    Compare <char>cmp3('a','A');

    cout<<cmp1.max()<<"is the Maximum of two INTEGER number."<<endl;

   cout<<cmp1.min()<<"is the Minimum of two INTEGER number."<<endl;

   cout<<cmp2.max()<<"is the Maximum of two DOUBLE number."<<endl;

   cout<<cmp2.min()<<"is theMinimum of two DOUBLE number."<<endl;

    cout<<cmp3.max()<<"is the Maximum of two CHAR number."<<endl;

    cout<<cmp3.min()<<"is the Maximum of twoCHAR number."<<endl;

}

<運算符重載——複數相加>

【運算符重載作爲類的成員函數】

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(double r=0,double i=0){real=r;imag=i;cout<<"object set"<<endl;};
    Complex operator+(Complex &c2);//運算符重載
    ~Complex(){cout<<"object free"<<endl;};
    void display();
private:
    double real;
    double imag;
};

Complex Complex::operator+(Complex &c2)//返回值爲對象
{
    Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}

void main()
{
    Complex c1(3,4),c2(5,-10),c3;
    c3=c1+c2;//運算符重載
    cout<<" c1=";c1.display();
    cout<<" c2=";c2.display();
    cout<<" c1+c2=";c3.display();
}

【運算符重載作爲友元函數時,程序的一些修改】

class Complex
{
public:
    Complex(double r=0,double i=0){real=r;imag=i;cout<<"object set"<<endl;};
    friend Complex operator+(Complex &c1,Complex &c2);//運算符重載
    ~Complex(){cout<<"object free"<<endl;};
    void display();
private:
    double real;
    double imag;
};

Complex operator+(Complex &c1,Complex &c2)
{
    Complex c;
    c.real=c1.real+c2.real;
    c.imag=c1.imag+c2.imag;
    return c;
}

<運算符重載——">>/<<">

#include <iostream>
using namespace std;

class Complex
{
public:
    Complex(double r=0,double i=0):real(r),imag(i){};//參數列表初始化構造函數
    friend ostream & operator <<(ostream &,Complex &);//作爲友元函數聲明重載運算符"<<"
    friend istream & operator >>(istream &,Complex &);//作爲友元函數聲明重載運算符">>"
private:
    double real;
    double imag;
};

ostream & operator <<(ostream &output,Complex &c)
{
    output<<"("<<c.real;
    if(c.imag>=0)
        output<<"+";
    output<<c.imag<<"i)";
    return output;
}
istream & operator>>(istream &input,Complex &c)
{
    cout<<"input real part and imaginary part of complex number:";
    input>>c.real>>c.imag;
    return input;
}

 void main()
 {
    Complex c1,c2;
    cin>>c1>>c2;
    cout<<"c1="<<c1<<endl;
    cout<<"c2="<<c2<<endl;
 }


<派生類構造函數對基類、對象、和派生類成員初始化>

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

class Student
{
public:
    Student(int n,string nam);
    void display();
protected:
    int num;
    string name;
};
class Student1:public Student
{
public:
    Student1(int,string,int,string,int,string);
    void show();
    void show_monitor();
private:
    Student monitor;//定義了一個基類子對象
    int age;
    string addr;
};

Student::Student(int n,string nam):num(n),name(nam){};
void Student::display()
{
        cout<<"num:"<<num<<endl;
        cout<<"name:"<<name<<endl;
}
Student1::Student1(int n,string nam,int n1,string nam1,int a,string ad):Student(n,nam),monitor(n1,nam1),age(a),addr(ad){};
void Student1::show()
{
        cout<<"This student is :"<<endl;
        display();
        cout<<"age:"<<age<<endl;
        cout<<"address:"<<addr<<endl;
}
void Student1::show_monitor()
{
        cout<<"Class monitor is :"<<endl;
        monitor.display();
}

 void main()
 {
    Student1 stud1(10010,"Wang_Ning",10001,"Li_sun",19,"115Beijing Road.Shanghai");
    stud1.show();
    stud1.show_monitor();
 }

【多繼承派生類的構造函數初始化

*class Student{};
*class Student1:public Student{};
*class Student2:public Student1{};

Student::Student(int num,string name);
Student1::Student1(int n,string name,int a):Student(n,nam){};
Student2::Student2(int n,string nam,int a,int s):Student1(n,nam,a){};


<多重繼承中的虛基類>

#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
    Person(string nam,char s,int a):name(nam),sex(s),age(a){};
protected:
    string name;
    char sex;
    int age;
};
class Teacher:virtual public Person
{
public:
    Teacher(string nam,char s,int a,string t):Person(nam,s,a),title(t){};
protected:
    string title;
};
class Student:virtual public Person
{
public:
    Student(string nam,char s,int a,float sco):Person(nam,s,a),score(sco){};
protected:
    float score;
};
class Graduate:public Teacher,public Student
{
public:
   //構造函數要對Person類初始化   

    Graduate(string nam,int a,char s,string t,float sco,float w):Person(nam,s,a),Teacher(nam,s,a,t),Student(nam,s,a,sco),wage(w){};
    void Graduate::show()
    {
        cout<<"name:"<<name<<endl;
        cout<<"age:"<<age<<endl;
        cout<<"sex:"<<sex<<endl;
        cout<<"score:"<<score<<endl;
        cout<<"title:"<<title<<endl;
        cout<<"wage:"<<wage<<endl;
    }
private:
    float wage;
};

void main()
{
    Graduate grad1("Wang-li",24,'f',"assistant",89.5,1234.5);
    grad1.show();
}


<多態性——靜態多態性+動態多態性+純虛函數+抽象類>

#include <iostream>
using namespace std;

class Shape                                                                                                  //聲明抽象基類
{
public:
    virtual float area()const=0;
    virtual void shapeName()const=0;

};

class Point:public Shape
{
public:
    Point(float,float);
    void setPoint(float,float);
    float getX()const{return x;}
    float getY()const{return y;}
    friend ostream & operator <<(ostream &,const Point &);
    virtual float area()const {return 0;};                                                             //必須要有,否則編譯報錯
    virtual void shapeName()const{cout<<"Point:";};                                       //對虛函數進行在定義
protected:
    float x;
    float y;
};

class Circle:public Point
{
public:
    Circle(float,float,float);
    void setRadius(float);
    float getRadius()const;
    virtual float area()const;
    friend ostream &operator<<(ostream &,const Circle &);
    virtual void shapeName()const{cout<<"Circle:";};                                        //對虛函數進行在定義
protected:
    float radius;
};

class Cylinder:public Circle
{
public:
    Cylinder(float,float,float,float);
    void setHeight(float);                                                                                  //不能聲明成const類型,會報錯
    float getHeight()const;
    virtual float area()const;
    float volume()const;
    friend ostream &operator <<(ostream &,const Cylinder &);
    virtual void shapeName()const{cout<<"Cylinder:";};                                   //對虛函數進行在定義
private:
    float height;
};

Point::Point(float a=1,float b=1):x(a),y(b){};
void Point::setPoint(float a,float b)
{
    x=a;
    y=b;
}
ostream & operator <<(ostream &output,const Point &p)
{
    output<<"center=["<<p.x<<","<<p.y<<"]"<<endl;
    return output;
}

Circle::Circle(float a=1,float b=1,float r=1):Point(a,b),radius(r){};
void Circle::setRadius(float r)
{
    radius=r;
}
float Circle::getRadius()const{return radius;}
float Circle::area()const
{
    return 3.1415*radius*radius;
}
ostream &operator <<(ostream &output,const Circle &c)
{
    output<<"Center=["<<c.x<<","<<c.y<<"],r="<<c.radius<<",area="<<c.area()<<endl;
    return output;
}

Cylinder::Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){};
void Cylinder::setHeight(float h)
{
    height=h;
}
float Cylinder::getHeight()const
{
    return height;
}
float Cylinder::area()const
{
    return 2*3.1415*Circle::area()+2*3.1415*radius*height;
}
float Cylinder::volume()const
{
    return Circle::area()*height;
}
ostream &operator <<(ostream &output,const Cylinder &cy)
{
    output<<"center=["<<cy.x<<","<<cy.y<<"],r="<<cy.radius<<",h="<<cy.height<<",area="<<cy.area()<<",volume="<<cy.volume()<<endl;
    return output;
}

void main()
{
    Point point(3.2,4.5);
    Circle circle(2.4,1.2,5.6);
    Cylinder cylinder(3.5,6.4,5.2,10.5);
    point.shapeName();                                        //指定類名調用成員函數
    cout<<point<<endl;
    circle.shapeName();                                       //指定類名調用成員函數
    cout<<circle<<endl;
    cylinder.shapeName();                                   //指定類名調用成員函數
    cout<<cylinder<<endl<<endl;

    Shape *pt;
    pt=&point; 
    pt->shapeName();                                         //利用基類指針調用成員函數

    cout<<point<<endl;
    pt=&circle;
    pt->shapeName();                                        //利用基類指針調用員函數
    cout<<circle<<endl;
    pt=&cylinder;
    pt->shapeName();                                        //利用基類指針調用成員函數
    cout<<cylinder<<endl;
    
    Point *pt;
    pt=&cylinder;
    pt->shapeName();
    cout<<*pt<<endl;                                       //利用基類指針實現運算符重載會有侷限性,能顯示運算符中派生類增加的數據成員

}

<多態性——基類與派生類的成員函數調用>

函數重載——函數名相同,但形參個數、形參類型不同

【指定基類名調用同名函數——函數名、形參個數、形參類型相同時,有侷限性】

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

class Student
{
public:
    Student(int,string,float);
    void display();
protected:
    int num;
    string name;
    float score;
};
class Graduate:public Student
{
public:
    Graduate(int,string,float,float);
    void display();
private:
    float pay;
};

Student::Student(int n,string nam,float s):num(n),name(nam),score(s){};
void Student::display()
{
    cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<endl;
}
Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){};
void Graduate::display()
{
    cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<",pay:"<<pay<<endl;
}

void main()
{
    //Student stud1(1001,"Li",87.5);
    Graduate grad1(2001,"Wang",98.5,7800);
    //stud1.display();
    grad1.Student::display();
    grad1.Graduate::display();//只能輸出派生類中未增加的基類成員

}

利用基類指針或引用——函數名、形參個數、形參類型相同時,有侷限性

#include <iostream>
 .  .  .

void main()
{
    Graduate grad1(2001,"Wang",98.5,7800);
    Student *p_Stu;
    p_Stu=&grad1;
    p_Stu->display();//派生類對象地址賦值給指向基類的指針,輸出的數據不能使派生類增加的;
    Graduate *p_Gra;
    p_Gra=&grad1;
    p_Gra->display();//派生類對象地址賦值給指向派生類的指針;

}

利用基類指針或引+虛函數——函數名、形參個數、形參類型相同時

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

class Student
{
public:
    Student(int,string,float);
    virtual void display();//聲明display函數爲虛函數
protected:
    int num;
    string name;
    float score;
};
class Graduate:public Student
{
public:
    Graduate(int,string,float,float);
    void display();
private:
    float pay;
};

Student::Student(int n,string nam,float s):num(n),name(nam),score(s){};
void Student::display()
{
    cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<endl;
}
Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){};
void Graduate::display()
{
    cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<",pay:"<<pay<<endl;
}

void main()
{
    Graduate grad1(2001,"Wang",98.5,7800);
    Student *p_Stu;
    p_Stu=&grad1;
    p_Stu->display();
//派生類對象地址賦值給指向基類的指針,派生類增加的數據也輸出

    Graduate *p_Gra;
    p_Gra=&grad1;
    p_Gra->display();
}

<指向基類指針與指向派生類指針調用派生類的不同>

#include <iostream>
using namespace std;
class Point
{
public:
    Point()
    {
        cout<<"executing Point contructor"<<endl;
    }
    ~Point()
    {
        cout<<"executing Point destructor"<<endl;
    }
};
class Circle:public Point
{
public:
    Circle()
    {
        cout<<"executing Circle contructor"<<endl;
    }
    ~Circle()
    {
        cout<<"executing Circle destructor"<<endl;
    }
};

void main()
{
    Point *p=new Circle;
    delete p;
    cout<<endl;
    Circle *c=new Circle;
    delete c;
}

結果:

【虛析構函數】

.  .  .  

virtual ~Point()
    {
        cout<<"executing Point destructor"<<endl;
    }

.  .  .

結果:

<流文件中:peek函數+putback函數+get函數+ignore函數>

#include <iostream>
using namespace std;
void main()
{
    char c[50],k;
    cout<<"please enter a sentence:";
    cin.get(c,50,'/');                                             //取49(50-1)個字符給字符數組c[50],遇到'/'時停止
    cout<<"The first part is:"<<c<<endl;         //可以使用"cout<<c"輸出字符數組中的元素;

    k=cin.peek();                                                 //將字符指針指向的下一個字符取出給k,並且字符指針的位置不移動
    cout<<"The next character is:"<<k<<endl;
    cin.putback('W');                                          //將'W'插入到下一個cin.get流中
    cin.ignore();                                                   //忽略一個字符
    cin.get(c,50,'*');                                             //繼續在終端生取字符,關鍵是在putback()和ignore()函數之後
    cout<<"The second part is:"<<c<<endl;
}

結果:

#include <iostream>
using namespace std;
void main()
{
    char c[50],k;
    cout<<"please enter a sentence:";
    cin.get(c,50,'/');
    cout<<"The first part is:"<<c<<endl;
    k=cin.peek();
    cout<<"The next character is:"<<k<<endl;
    cin.ignore();
    cin.putback('W');

    cin.get(c,50,'*');
    cout<<"The second part is:"<<c<<endl;
}

結果:

<文件流的操作>

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
    ofstream outfile("../data1.dat",ios::out);   //注意用雙引號,相對路徑爲“../data.dat”
    string str
    if(!outfile)
    {
        cerr<<"open failed!"<<endl;
        exit(1);
    }
    cout<<"enter a sentence:";
    cin>>str;
    outfile<<str;                                                  //輸出到文件,string類型遇空格則停止讀入
    outfile.close();
}

【輸入帶空格的字符串
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
    ofstream outfile("../data1.dat",ios::out);   //注意用雙引號,相對路徑爲“../data.dat”
    char ch[100];
    if(!outfile)
    {
        cerr<<"open failed!"<<endl;
        exit(1);
    }
    cout<<"enter a sentence:";
    outfile<<gets(ch);                                       //輸出到文件,可以讀入空格,直到回車送入緩衝區
    outfile.close();
}

<二進制文件讀寫操作與seekp函數與seekg函數>

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

struct student
{
    int num;
    char name[20];
    float score;
};

void main()
{
    student stud[5]={1001,"Li",85,1002,"Wu",97.5,1003,"Wang",54,1004,"Tan",76.5,1005,"Ling",96};
    int index;
    fstream iofile("stud.dat",ios::in|ios::out|ios::binary);                  //由於涉及到文件的讀取和寫入操作,所以
    if(!iofile)
    {
        cerr<<"open failed!"<<endl;
        exit(1);
    }
    for(int i=0;i<5;i++)
        iofile.write((char *)&stud[i],sizeof(stud[i]));
    
    /*輸出指定成員信息*/
    student cc;
    cout<<"the date index to be read:";
    cin>>index;
    iofile.seekg(index*sizeof(stud[0]),ios::beg);                                 //將讀文件指針定位到將要讀的字符處
    iofile.read((char *)&cc,sizeof(cc));                                                //二進制文件讀操作
    cout<<cc.num<<" "<<cc.name<<" "<<cc.score<<endl;
    
    /*修改成員數據*/
    stud[2].num=2012;
    strcpy(stud[2].name,"Xu");
    stud[2].score=100;
    iofile.seekp(2*sizeof(stud[0]),ios::beg);                                        //將寫文件指針定位到將要修改的字符處
    iofile.write((char *)&stud[2],sizeof(stud[2]));                               //二進制文件寫操作
    
    /*輸出修改過後的所有成員數據*/

    iofile.seekg(0,ios::beg);                                                                //恢復讀文件指針的位置,以便read輸出所有成員信息
    for(int i=0;i<5;i++)
    {
        iofile.read((char *)&stud[i],sizeof(stud[i]));
        cout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<endl;
    }
    iofile.close();
}

<字符串流的使用>

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

void main()
{
    char ch[50]="12 34 65 -23 -32 33 61 99 321 32";//字符數組的賦值
    int a[10],i,j,temp;
    istrstream strin(ch,sizeof(ch));                       //將數組ch字符與字符串輸入流關聯
    cout<<"ch:"<<ch;
    for(i=0;i<10;i++)
        strin>>a[i];
    cout<<endl;
    cout<<"a:";
    for(i=0;i<10;i++)
    {
        cout<<a[i]<<" ";
    }
    for(i=0;i<10;i++)
    {
        for(j=i+1;j<10;j++)
        {
            if(a[j]>a[i])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    ostrstream strout(ch,sizeof(a));                       //將數組ch字符與字符串輸出流關聯
    for(i=0;i<10;i++)
        strout<<a[i]<<" ";
        cout<<endl;
    cout<<"order ch:"<<ch<<endl;
    system("pause");
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章