C++語言基礎(4)-建構函式和解構函式

來源:互聯網
上載者:User

標籤:年齡   自己   支援   public   初始化   cout   語言   傳參   float   

 

一.建構函式的定義

類似於java,C++中也有建構函式的概念,相關用法如下:

1.1 建構函式的定義

#include <iostream>using namespace std;class Student{private:    char *m_name;    int m_age;    float m_score;public:    //聲明建構函式    Student(char *name, int age, float score);    //聲明普通成員函數    void show();};//定義建構函式Student::Student(char *name, int age, float score){    m_name = name;    m_age = age;    m_score = score;}//定義普通成員函數void Student::show(){    cout<<m_name<<"的年齡是"<<m_age<<",成績是"<<m_score<<endl;}int main(){    //建立對象時向建構函式傳參    Student stu("小明", 15, 92.5f);    stu.show();    //建立對象時向建構函式傳參    Student *pstu = new Student("李華", 16, 96);    pstu -> show();    return 0;}

運行結果:

小明的年齡是15,成績是92.5
李華的年齡是16,成績是96

1.2 建構函式的重載

建構函式同樣也支援重載操作:

#include <iostream>using namespace std;class Student{private:    char *m_name;    int m_age;    float m_score;public:    Student();    Student(char *name, int age, float score);    void setname(char *name);    void setage(int age);    void setscore(float score);    void show();};Student::Student(){    m_name = NULL;    m_age = 0;    m_score = 0.0;}Student::Student(char *name, int age, float score){    m_name = name;    m_age = age;    m_score = score;}void Student::setname(char *name){    m_name = name;}void Student::setage(int age){    m_age = age;}void Student::setscore(float score){    m_score = score;}void Student::show(){    if(m_name == NULL || m_age <= 0){        cout<<"成員變數還未初始化"<<endl;    }else{        cout<<m_name<<"的年齡是"<<m_age<<",成績是"<<m_score<<endl;    }}int main(){    //調用建構函式 Student(char *, int, float)    Student stu("小明", 15, 92.5f);    stu.show();    //調用建構函式 Student()    Student *pstu = new Student();    pstu -> show();    pstu -> setname("李華");    pstu -> setage(16);    pstu -> setscore(96);    pstu -> show();    return 0;}

運行結果:

小明的年齡是15,成績是92.5
成員變數還未初始化
李華的年齡是16,成績是96

1.3 預設建構函式

類似於java,如果使用者自己沒有定義建構函式,那麼編譯器會自動產生一個預設的建構函式,只是這個建構函式的函數體是空的。

注意:調用沒有參數的建構函式也可以省略括弧。

Student *stu  = new Student;

Student *stu = new Student();

以上兩種寫法是等價的。

 

C++語言基礎(4)-建構函式和解構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.