C++基礎(類和構造函數(shù))

C++基礎

類和構造函數(shù)

  • 類:類是定義同一類所有對象得變量和方法的藍圖或原型挤庇。數(shù)據(jù)與算法的統(tǒng)一拷邢。

    • 成員
    • 成員函數(shù)
    • 保護數(shù)據(jù)
    • 封裝
  • 類和對象就像人類與人的關系

  • 對象的初始化

    • 建立對象奄喂,須有一個有意義的初始值
    • C++建立和初始化對象的過程專門由該類的構造函數(shù)來完成梳杏。
    • 構造函數(shù)給對象分配空間和初始化们童。
    • 如果一個類沒有專門定義構造函數(shù)权谁,那么C++就僅僅創(chuàng)建對象而不做任何初始化
#include <iostream>
using namespace std;
class Person
{
    private:
        int id;
        int money;
    public:
        void show()
        {
            cout<<"id="<<id<<"money="<<money<<endl;
        }
        void set(int a,int b)
        {
            if(a<0)
                a=0;
            id=a;
            money=b;
        }
};
int main()
{
    Person a;
    Person b;
    a.set(1,100);
    a.show();
    b.set(2,300);
    b.show();
}
class Person
{
    private:
        int id;
        int money;
    public:
        void show();
        void set(int a,int b);
};
void Person::show()
{
    cout<<"id="<<id<<"money="<<money<<endl;
}
void Person::set(int a,int b)
{
    if(a<0)
        a=0;
    id=a;
    money=b;
}
  • 最終版
//main.cpp
#include "person.h"
int main()
{
    Person a;
    Person b;
    a.set(1,100);
    a.show();
    b.set(2,300);
    b.show();
}
//person.cpp
#include <iostream>
#include "person.h"
using namespace std;
void Person::show()
{
    cout<<"id="<<id<<"money="<<money<<endl;
}
void Person::set(int a,int b)
{
    if(a<0)
        a=0;
    id=a;
    money=b;
}
//person.h
#include "person.h"
class Person
{
    private:
        int id;
        int money;
    public:
        void show();
        void set(int a,int b);
};
  • class默認私有。

  • 面向對象

    • 在面向對象中贴谎,算法與數(shù)據(jù)結構被捆綁為一類
  • 定義成員函數(shù)

    • 類中定義成員函數(shù)一般為頭連函數(shù)汞扎,即沒有明確用。擅这。澈魄。。仲翎。痹扇。。溯香。鲫构。
  • 保護成員

    • 保護成員
      • 除了友元和子類的成員函數(shù)之外,從類的外部就不能對它們訪問
    • 私有成員
      • 從類的外部就不能對它們訪問
    • 公共成員
      • 公共成員在任何地方都可以被訪問。
  • 不同域對應不同的函數(shù)內容

#include <iostream>
using namespace std;        
class person
{
    private:
        int id;
        int money;
    public:
        void show();
        void show(int a);
};
class test
{
    public:
        void show();
};
void person::show()
{
    cout<<"hello1"<<endl;
}
void person::show(int a)
{
    cout<<"hello2"<<endl;
}
void test::show()
{
    cout<<"hello3"<<endl;
}
void show()
{
    cout<<"hello4"<<endl;
}
int main()
{
    person a;
    test b;
    a.show();
    a.show(1);
    show();
    b.show();
}
  • 對象與域的調用方法
#include <iostream>
using namespace std;
class test
{
    public:
        void show()
        {
            cout<<"hello"<<endl;
        }
};
void lianxi1(test *p1)
{
    p1->show();
}
void lianxi2(test &p2)
{
    p2.show();
}
void lianxi3(test p3)
{
    p3.show();
}
int main()
{
    test t;
    lianxi1(&t);
    lianxi2(t);
    lianxi3(t);
    cout<<sizeof(test)<<endl;
}
#include <iostream>
using namespace std;        
class test
{
    private:
        int id;
    public:
        void setid(int i)
        {
            id=i;
        }
        void show()
        {
            cout<<"this"<<(this)<<endl;
            cout<<"id= "<<(id)<<endl;
        }       
};
int main()
{
    test t;
    t.setid(222);
    t.show();
    cout<<"&t="<<&t<<endl;

}
  • 類和struct的區(qū)別
    • 除關鍵字不同外(class,struct)的唯一區(qū)別是,結構在默認情況下的成員是公共的,而類在默認情況下的成員是私有的玫坛。 在C++中,結構是特殊的類结笨。
  • 類的作用域
    • 一個類的所有成員位于這個類的作用域內
    • 類作用域是類定義和相應類成員定義范圍
  • 對象和類的聯(lián)系與區(qū)別

  • 類中訪問控制的關鍵字有哪幾個,分別是什么意義

  • 封裝理念
    • 封裝來源于信息隱藏的設計理念湿镀, 是通過特性和行為的組合來創(chuàng)建新數(shù)據(jù)類型讓接口與具體實現(xiàn)相隔離炕吸。
    • C++中是通過類來實現(xiàn)的, 為了盡量避免某個模塊的行為干擾同一系統(tǒng)中的其它模塊肠骆,應該讓模塊僅僅公開必須讓外界知道的接口。
  • 封裝的優(yōu)點
    • 重用
    • 不必關心具體的體現(xiàn)
    • 具有安全性

構造函數(shù)

  • 定義
    • C++的構造函數(shù)和析構塞耕,使類對象能輕松的被賦值與撤銷蚀腿。它們是一種特殊的函數(shù)。
    • 構造函數(shù)是第一個自動調用的函數(shù)
    • 構造函數(shù)創(chuàng)建類對象,初始化其成員
    • 析構函數(shù)撤銷類對象
    • 構造函數(shù)和析構函數(shù)是類的特殊成員函數(shù)
    • 與類同名
    • 析構函數(shù)
    • 重載構造函數(shù)
    • 默認參數(shù)構造函數(shù)
    • 對象創(chuàng)建過程
#include<iostream>
using namespace std;
class Fract
{
    int m_m;
    int m_z;
public:
      Fract(int z,int m);
      Fract();
      void set(int z,int m)
      {
        m_m=m;
        m_z=z;
      }//set函數(shù)依舊保留莉钙,以防后續(xù)使用廓脆。
      void print()
      {
        reduce();
        cout<<m_z<<"/"<<m_m<<endl;
      }
      void reduce()
      {
        for(int i=m_m;i>0;i--)
        {
            if((m_m%i==0)&&(m_z%i==0))
            {
                m_m/=i;
                m_z/=i;
                break;
            }
        }
      }
};
Fract::Fract(int z,int m)
{
    m_m=m;
    m_z=z;
}
Fract::Fract()
{
    m_m=12;
    m_z=16;
    //-cout<<"hello"<<endl;
}
int main()
{
    Fract a(12,16);
//  a.set(12,16);
    a.print();
    Fract b;//一般不用(),會出錯。
//  a.set(12,16);
    b.print();
    //-Fractc[5];會調用5次
}
  • 注意
    • 類名==構造函數(shù)名
    • 構造函數(shù)沒有返回值類型磁玉,函數(shù)體也不允許返回值停忿,但可以有返回語句"return".
  • 建立對象的同時,自動調用構造函數(shù)
#include <iostream>
using namespace std;
class test1
{
    public:
        test1()
        {   
            cout<<"hello test1"<<endl;
        }
        
};
class test2
{
    test1 m_t;
    public:
        test2()
        {
            cout<<"hello test2"<<endl;
        }
};
int main()
{
    test2 t;
}
  • 類中成員變量也是類蚊伞,調用順序:
#include <iostream>
using namespace std;
class test1
{
    int m_a;
    public:
        test1(int a)
        {   
            m_a=a;
            cout<<"hello test1"<<m_a<<endl;
        }
        test1(){}
};
class test2
{
    test1 m_t;
    test1 m_s;
    public:
        test2()
        {
            cout<<"hello test2"<<endl;
        }
};
int main()
{
    test2 t;
}
//test2()后調用賦值11出現(xiàn)hello test111+hello test2
//不調用則出現(xiàn)hello test2
#include <iostream>
using namespace std;
class test1
{
    int m_a;
    public:
        test1(int a)//
        {   
            m_a=a;
            cout<<"hello test1"<<m_a<<endl;
        }
        test1(){}
        ~test()
        {
            cout<<"析構測試1"<<endl;
        }
};
class test2
{
    test1 m_t;
    test1 m_s;
    public:
        test2():m_s(222),m_t(333)
        {
            cout<<"hello test2"<<endl;
        }   
        ~test2()
        {
            cout<<"析構測試2"<<endl;
        }
        
};
int main()
{
    test2 t;
    cout<<"+++"<<endl;
}
//hello test1333
//hello test1222
//hello test2
//+++
//析構測試2
//析構測試1222
//析構測試1333
  • 析構函數(shù)

    • 在t消亡的時候自動調用席赂,無返回值。
    • 析構函數(shù)不允許重載时迫。
    • 析構函數(shù)有且只有一個颅停。
    • 析構函數(shù)是特殊的類成員函數(shù),不能隨意調用
  • 析構函數(shù)之防止內存泄漏

#include <iostream>
#include <malloc.h>
using namespace std;
class test
{
    int *p;
    public:
        test()
        {
            p=(int *)malloc(sizeof(int));
            *p=4;
            cout<<"test construct"<<endl;
        }
        ~test()
        {
            free(p);
            cout<<"析構測試"<<endl;
        }
        void print()
        {
            cout<<*p<<endl;
        }
};
int main()
{
    test t;
    t.print();
    cout<<"+++++++"<<endl;
}
//test construct
//4
//++++++
//析構測試
  • 手動創(chuàng)建構造函數(shù)是創(chuàng)建一個無名函數(shù)

  • C++給構造對象的順序做了專門的規(guī)定

    • 局部和靜態(tài)對象掠拳,以聲明順序構造
    • 靜態(tài)對象只能被構造一次
    • 所有全局對象都在主函數(shù)main()之前被構造
    • 全局對象構造時無特殊順序
    • 成員以其在類聲明的順序構造
  • 構造函數(shù)在分配空間之后被調用

bool型變量

#include <iostream>
using namespace std;
int main()
{
    bool bSex=true;
    cout<<"請輸入數(shù)字"<<endl;
    cin>>bSex;
    cout<<"我叫SB,是一位"<<(bSex?"丑逼":"帥逼")<<endl;
    cout<<"true="<<true<<endl;
    cout<<"false="<<false<<endl;
}
  • 分配與釋放順序
#include <iostream>
using namespace std;
class test
{
    int m_data;
    public:
        test(int data):m_data(data)
        {
            cout<<"test("<<m_data<<")"<<endl;
        }
        ~test()
        {
            cout<<"~test("<<m_data<<")"<<endl;
        }
};
test t1(10);
void fun()
{
    test t4(40);
    return;
}
void show()
{
    static test t5(50);
    return;
}
int main(int argc,char **argv)
{
    test t2(20);
    test t3(30);
    fun();
    show();
}
test t6(60);
  • 類和構造函數(shù)制造時鐘
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
class myClock
{
    private:
        int myHour;
        int myMin;
        int mySecond;
    public:
        myClock();
    //  void set(int hour,int min,int second);
        void Time();
        void show();
        void run();
};
myClock::myClock():myHour(23),myMin(59),mySecond(55)
{
}
/*
void myClock::set(int hour,int min,int second)
{
    myHour=hour;
    myMin=min;
    mySecond=second;
}*/
void myClock::Time()
{

        sleep(1);
        mySecond++;
        if(mySecond==60)
        {   
            myMin++;
            if(myMin==60)
            {
                myHour++;
                if(myHour==24)
                {
                    myHour=0;
                }
                myMin=0;
            }
            mySecond=0;
        }
    
}
void myClock::show()
{
    cout<<myHour<<":"<<myMin<<":"<<mySecond<<endl;
}
void myClock::run()
{
    while(1)
    {
        system("clear");
        show();
        Time();
    }
}
int main()
{
    myClock c;
//  c.set(23,59,55);
    c.run();
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末癞揉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子溺欧,更是在濱河造成了極大的恐慌喊熟,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件姐刁,死亡現(xiàn)場離奇詭異芥牌,居然都是意外死亡,警方通過查閱死者的電腦和手機龙填,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進店門胳泉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人岩遗,你說我怎么就攤上這事扇商。” “怎么了宿礁?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵案铺,是天一觀的道長。 經常有香客問我梆靖,道長控汉,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任返吻,我火速辦了婚禮姑子,結果婚禮上,老公的妹妹穿的比我還像新娘测僵。我一直安慰自己街佑,他們只是感情好谢翎,可當我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著沐旨,像睡著了一般森逮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上磁携,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天褒侧,我揣著相機與錄音,去河邊找鬼谊迄。 笑死闷供,一個胖子當著我的面吹牛,可吹牛的內容都是我干的鳞上。 我是一名探鬼主播这吻,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼篙议!你這毒婦竟也來了唾糯?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鬼贱,失蹤者是張志新(化名)和其女友劉穎移怯,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體这难,經...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡舟误,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了姻乓。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嵌溢。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖蹋岩,靈堂內的尸體忽然破棺而出赖草,到底是詐尸還是另有隱情,我是刑警寧澤剪个,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布秧骑,位于F島的核電站,受9級特大地震影響扣囊,放射性物質發(fā)生泄漏乎折。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一侵歇、第九天 我趴在偏房一處隱蔽的房頂上張望骂澄。 院中可真熱鬧,春花似錦惕虑、人聲如沸坟冲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽樱衷。三九已至,卻和暖如春酒唉,著一層夾襖步出監(jiān)牢的瞬間矩桂,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工痪伦, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留侄榴,地道東北人。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓网沾,卻偏偏與公主長得像癞蚕,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子辉哥,可洞房花燭夜當晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內容