首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 基礎知識回顧:構造函數、析構函數與常引用詳解

     編輯:關於C++

一、構造函數與析構函數

構造函數在創建對象時自動調用,用於初始化成員;析構函數在對象銷毀時自動調用,釋放資源。兩者均無返回值,名字分別為類名與 ~類名。

示例:學生類

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

class Student {
public:
    // 使用初始化列表
    Student(string name, int age, float score)
        : name(name), age(age), score(score) {}

    ~Student() { cout << name << "再見" << endl; }

    void say() const { cout << name << "的年齡是 " << age << ",成績是 " << score << endl; }

private:
    string name;
    int age;
    float score;
};

int main() {
    Student s1("小明", 15, 90.5f);
    Student s2("李磊", 16, 95);
    Student s3("王爽", 16, 80.5f);
    s1.say(); s2.say(); s3.say();
    cout << "main 即將結束" << endl;
    return 0;
}

輸出順序:三個 say()、main 即將結束、三個析構函數(逆序銷毀)。

二、對象的常引用

常引用參數 const T& 兼具「避免拷貝」與「防止修改」優勢:

  • 傳遞大型對象時無拷貝開銷。
  • 編譯器保證函數內不修改實參。
  • 可綁定臨時對象(右值),延長其生命週期至函數結束。

代碼示範

#include <iostream>
using namespace std;

class Time {
public:
    Time(int h, int m, int s) : hour(h), minute(m), sec(s) {}
    int hour, minute, sec;
};

// 常引用參數
void printTime(const Time& t) {
    cout << t.hour << ':' << t.minute << ':' << t.sec << endl;
}

int main() {
    Time t1(10, 13, 56);
    printTime(t1);           // 傳遞左值
    printTime(Time(12, 0, 0)); // 傳遞右值臨時對象,合法
    return 0;
}

三、總結

  • 構造/析構是資源管理基石,善用初始化列表。
  • 常引用是函數參數傳遞的首選形式(除非需要修改實參)。
  • 理解對象生命週期,避免懸空引用與雙重釋放。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved