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

C++11 核心特性解析:string 字符串類型與 auto 類型推導

     編輯:C++ 入門

從字符數組到 std::string:C++ 風格的字符串處理

C 風格字符串的痛點

char msg[32];
msg[0]='G'; msg[1]='o'; msg[2]='o'; msg[3]='d'; msg[4]='\0';
cout << msg;
  • 固定緩衝區,易溢出
  • 手動管理結束符 '\0'
  • 拼接、查找、比較全靠 cstring 繁瑣函數

std::string:自動管理內存的字符序列

#include <string>
using namespace std;

string s = "Good Morning!";
cout << s.length() << endl;  // 13
cout << s.find("Mor") << endl; // 5
s += " World";                  // 直接拼接
  • 動態擴容,無緩衝區溢出風險
  • 豐富成員函數:length/size, find/rfind, substr, append, replace...
  • 支持 +, +=, ==, < 等運算符

寬字符版本 wstring

wstring ws = L"陝A-82103";  // L 前綴表寬字符串字面量
wcout.imbue(locale("chs")); // 設置中文區域
wcout << ws << endl;
  • string 對應 char(窄字符,通常 ASCII/UTF-8)
  • wstring 對應 wchar_t(寬字符,Windows 下 UTF-16,Linux 下 UTF-32)
  • 英文可用 string 或 wstring;中文建議用 wstring 避免編碼亂碼
  • 輸出用 wcout,需 imbue(locale) 設置正確區域

auto:讓編譯器幫你推導類型

動機:復雜類型寫起來太痛苦

auto x = 7;           // int
auto y = 1.982;       // double
auto p = new Foo();   // Foo*
auto f = [](int a){ return a*2; }; // lambda 閉包類型

兩種語法形式

  • 賦值形式:auto x = expr;
  • 列表初始化:auto x{expr}; (C++11 推導為 initializer_list,C++17 修正為單值類型)

必須有初始值

auto x; // 錯誤:無初始值無法推導

實戰場景:模板代碼簡化

template <typename T>
void printAll(const vector<T>& v) {
    for (auto it = v.begin(); it != v.end(); ++it)
        cout << *it << '\n';
    // 對比 C++98:
    // for (typename vector<T>::const_iterator it = v.begin(); ...)
}

更強大的場景:返回類型依賴模板參數

template <typename T, typename U>
auto mul(const T& a, const U& b) -> decltype(a*b) {
    return a * b;  // 返回類型由 a*b 推導
}

配合尾置返回類型 -> decltype(...),解決「模板函數返回類型無法預知」的難題。

decltype:獲取表達式類型,而不求值

int x = 3;
decltype(x) y = 5;        // int
decltype((x)) z = y;      // int& (加括號變左值表達式)
decltype(x+0.0) w = 1.5;  // double
  • auto:根據初始值推導變量類型,用於變量定義
  • decltype:根據表達式推導類型,用於類型聲明、返回類型、typedef

典型用法:為復雜類型起別名

template <typename T, typename U>
void foo(const T& a, const U& b) {
    typedef decltype(a*b) ResultType;  // 獲得乘法結果類型
    ResultType* p = new ResultType();  // 用於定義指針、創建對象...
}

總結對比

特性autodecltype
推導依據初始值表達式的值表達式本身的類型
是否求值是(需初始化)否(僅編譯期分析)
主要用途變量定義簡化類型聲明、模板元編程
引用保留默認去除引用(auto& 保留)保留表達式的值類別(左值→引用)

最佳實踐建議

  1. 優先用 auto 定義變量,特別是迭代器、Lambda、模板代碼。
  2. 需要「類型作為類型」用到別處時,用 decltype + typedef/using。
  3. 模板函數返回類型依賴參數時,用 auto + 尾置 decltype(C++14 起可直接 auto 返回類型推導)。
  4. 避免濫用導致代碼不可讀:核心業務邏輯變量仍建議顯式寫類型。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved