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

MFC 核心類速查手冊:CRect、CPoint、CString 常用構造與成員函數

     編輯:關於C語言

CRect — 矩形幾何運算

構造函數

CRect(); 
CRect(int l, int t, int r, int b); 
CRect(const RECT& src); 
CRect(LPCRECT lpSrc); 
CRect(POINT pt, SIZE sz); 
CRect(POINT topLeft, POINT bottomRight);

核心屬性獲取

int Width() const; 
int Height() const; 
CSize Size() const; 
CPoint& TopLeft(); 
CPoint& BottomRight(); 
CPoint CenterPoint() const;

運算符重載

  • rect + point → 平移
  • rect + rect → 並集(外包矩形)
  • rect &= rect → 交集
  • rect |= rect → 並集
  • PtInRect(pt) → 點包含測試

CPoint — 二維點/向量

構造

CPoint(); 
CPoint(int x, int y); 
CPoint(POINT pt); 
CPoint(SIZE sz); 
CPoint(LPARAM dw); // 低字x,高字y

運算

  • pt1 + pt2、pt1 - pt2、pt += sz、pt -= sz
  • CSize operator-(POINT pt) → 向量差

CString — 可變長字符串(MFC 核心字符串類)

關鍵特性

  • 自動內存管理,書寫時複製(COW),支持 ANSI/Unicode 雙模式。
  • 隱式轉換 LPCTSTR,可直接傳給 API。
  • 格式化:str.Format(_T("Val=%d"), n)。

常用成員函數

函數說明
GetLength()字符數(不含結束符)
GetAt(int idx)單字符讀取
SetAt(int idx, TCHAR ch)單字符修改
operator[]雙向訪問 str[i]
Find(ch/substr)查找,返回索引或 -1
Replace(old, new)全局替換
Left(n)/Right(n)/Mid(pos, len)子串提取
MakeUpper()/MakeLower()大小寫轉換
Trim()/TrimLeft()/TrimRight()去除空白字符
Compare(str)/CompareNoCase(str)比較
operator+拼接 s1 + s2
LoadString(ID)從資源加載

CSize — 尺寸/向量

CSize(); CSize(int cx, int cy); CSize(SIZE sz); CSize(POINT pt); 
// cx=寬度, cy=高度, 支持 + - 與 CPoint 運算

實戰組合拳

CRect rc(10,10,100,80); 
CPoint pt = rc.CenterPoint(); // (55,45) 
CSize sz = rc.Size(); // (90,70) 
rc.DeflateRect(5,5); // 內縮 → (15,15,95,75) 
rc.OffsetRect(CSize(10,0)); // 右移 → (25,15,105,75) 
CString str; 
str.Format(_T("Rect: (%d,%d)-(%d,%d)"), rc.left, rc.top, rc.right, rc.bottom);

總結

CRect/CPoint/CSize 構成 MFC 坐標幾何運算體系,CString 解決字符串內存管理痛點。熟練掌握構造、屬性獲取、運算符重載與常用成員,能大幅減少 Windows 繪圖、佈局、字符串處理的樣板代碼。本文整理自 51CTO 博客「MFC中常用類,宏,函數介紹」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved