文章目錄
- 一、C的struct和C++的類的區別
- 二、關于OOP
- 三、舉例:一個商品類CGoods
- 四、構造函數和析構函數
- 1、定義一個順序棧
- 2、用構造和析構代替s.init(5);和s.release();
- 3、在不同內存區域構造對象
- 4、深拷貝和淺拷貝
- 5、構造函數和深拷貝的簡單應用
- 6、構造函數的初始化列表
- 五、類的各種成員變量和成員方法
- 1、普通成員變量、靜態成員變量
- 2、普通成員方法、靜態成員方法、常成員方法
- 六、指向類成員(成員變量和成員方法)的指針
一、C的struct和C++的類的區別
以下表格由DeepSeek-R1生成:
特性 | C 的 struct | C++ 的 struct | C++ 的 class |
---|---|---|---|
默認訪問權限 | 無(僅數據) | public | private |
成員函數 | 不支持 | 支持 | 支持 |
繼承/多態 | 不支持 | 支持 | 支持 |
構造/析構函數 | 不支持 | 支持 | 支持 |
模板 | 不支持 | 支持 | 支持 |
設計用途 | 純數據聚合 | 簡單數據+方法 | 封裝復雜對象行為 |
實際開發中,C++ 的 struct 和 class 僅默認權限不同,但習慣上用 struct 表示數據為主的結構,class 表示具有復雜行為的對象。
- 在C中:
各種各樣的函數的定義、struct - 在C++中:
實體(屬性、行為)????????????->????????????ADT(abstract data type)
對象????????????<-(實例化)???????類(屬性->成員變量行為->成員方法)
二、關于OOP
- Object Oriented Programming:面向對象程序設計
- OOP語言的四大特性:抽象、封裝/隱藏、繼承、多態
- 類中的訪問限定符:(由DeepSeek-R1生成)
基類成員訪問限定符 | 類內部訪問 | 繼承方式 | 派生類中基類成員的訪問權限 | 外部代碼訪問 | 友元訪問 |
---|---|---|---|---|---|
public | ? | public 繼承 | public | ? | ? |
protected 繼承 | protected | ? | ? | ||
private 繼承 | private | ? | ? | ||
protected | ? | public 繼承 | protected | ? | ? |
protected 繼承 | protected | ? | ? | ||
private 繼承 | private | ? | ? | ||
private | ? | 任何繼承方式 | 不可訪問 | ? | ? |
三、舉例:一個商品類CGoods
#include <iostream>
using namespace std;const int NAME_LEN = 20;class CGoods {
public: // 給外部提供公有的成員方法,來訪問私有的屬性// 商品數據初始化void init(const char *name, double price, int amount);// 打印商品信息void show();// 給成員變量提供getXXX或setXXX的方法(注意:類內部實現的方法,自動處理成inline內聯函數)void setName(const char *name) { strcpy_s(_name, sizeof(_name), name); }void setPrice(double price) { _price = price; }void setAmount(int amount) { _amount = amount; }const char *getName() { return _name; }double getPrice() { return _price; }int getAmount() { return _amount; }
private:char _name[NAME_LEN];double _price;int _amount;
};void CGoods::init(const char *name, double price, int amount) {strcpy_s(_name, sizeof(_name), name);_price = price;_amount = amount;
}void CGoods::show() {cout << "name: " << _name << endl;cout << "price: " << _price << endl;cout << "amount: " << _amount << endl;
}int main() {CGoods good1;good1.init("面包", 10.0, 200); good1.show();good1.setPrice(20.5); good1.setAmount(100); good1.show();CGoods good2;good2.init("空調", 10000.0, 50);good2.show();return 0;
}
注意:
- 類可以定義無數個對象,每一個對象都有自己的成員變量,但是它們共享一套成員方法。
- 類內部實現的方法,自動處理成inline內聯函數,外部則不會。
- 對象的內存大小,與成員變量有關。VS2022下可以通過cl C++面向對象.cpp /dlreportSingleClassLayoutCGoods查看占用內存大小。
- init(name,price,amount)怎么知道處理哪個對象的信息,把信息初始化給哪一個對象的呢?
類的成員方法一經編譯,所有的方法參數,都會加一個this指針,接收調用該方法的對象的地址。
void init(CGoods *this, const char *name, double price, double amount);void CGoods::init(CGoods *this, const char *name, double price, int amount) {strcpy_s(this->_name, sizeof(this->_name), name);this->_price = price;this->_amount = amount;}init(&good1, "面包", 10.0, 200);
四、構造函數和析構函數
1、定義一個順序棧
#include <iostream>
using namespace std;const int NAME_LEN = 20;class SeqStack {
public: void init(int size = 10) {_pstack = new int[size];_top = -1;_size = size;}void release() {delete[]_pstack;_pstack = nullptr;}void push(int val) {if (full()) {resize();}_pstack[++_top] = val;}void pop() {if (empty()) {return;}--_top;}int top() {return _pstack[_top];}bool empty() { return _top == -1; }bool full() { return _top == _size - 1; }private:int *_pstack;int _top;int _size;void resize() {int* ptmp = new int[_size * 2];for (int i = 0; i < _size; ++i) {ptmp[i] = _pstack[i];} // memcpy(ptmp, _pstack, sizeof(int)*size);或realloc可能產生深拷貝淺拷貝的問題delete[]_pstack;_pstack = ptmp;_size *= 2;}
};int main() {SeqStack s;s.init(5); for (int i = 0; i < 15; ++i) {s.push(rand() % 100);}while (!s.empty()) {cout << s.top() << " ";s.pop();}s.release();return 0;
}
2、用構造和析構代替s.init(5);和s.release();
#include <iostream>
using namespace std;const int NAME_LEN = 20;class SeqStack {
public: SeqStack(int size = 10) { // 構造函數可帶參數,可以重載_pstack = new int[size];_top = -1;_size = size;}~SeqStack() { // 不帶參數,只能有一個delete[]_pstack;_pstack = nullptr;}void push(int val) {if (full()) {resize();}_pstack[++_top] = val;}void pop() {if (empty()) {return;}--_top;}int top() {return _pstack[_top];}bool empty() { return _top == -1; }bool full() { return _top == _size - 1; }private:int *_pstack;int _top;int _size;void resize() {int* ptmp = new int[_size * 2];for (int i = 0; i < _size; ++i) {ptmp[i] = _pstack[i];} // memcpy(ptmp, _pstack, sizeof(int)*size);或realloc可能產生深拷貝淺拷貝的問題delete[]_pstack;_pstack = ptmp;_size *= 2;}
};int main() {//1.開辟內存 2.調用構造函數SeqStack s(5);//s.init(5); // 對象成員變量的初始化for (int i = 0; i < 15; ++i) {s.push(rand() % 100);}while (!s.empty()) {cout << s.top() << " ";s.pop();}//s.release(); // 釋放對象成員變量占用的外部堆內存(外部資源)return 0;
}
3、在不同內存區域構造對象
#include <iostream>
using namespace std;const int NAME_LEN = 20;class SeqStack {
public: SeqStack(int size = 10) {cout << this << " SeqStack" << endl;_pstack = new int[size];_top = -1;_size = size;}~SeqStack() {cout << this << " ~SeqStack" << endl;delete[]_pstack;_pstack = nullptr;}void push(int val) {if (full()) {resize();}_pstack[++_top] = val;}void pop() {if (empty()) {return;}--_top;}int top() {return _pstack[_top];}bool empty() { return _top == -1; }bool full() { return _top == _size - 1; }private:int *_pstack;int _top;int _size;void resize() {int* ptmp = new int[_size * 2];for (int i = 0; i < _size; ++i) {ptmp[i] = _pstack[i];} // memcpy(ptmp, _pstack, sizeof(int)*size);或realloc可能產生深拷貝淺拷貝的問題delete[]_pstack;_pstack = ptmp;_size *= 2;}
};/*
.data
heap
stack
*/
SeqStack s0; //.dataint main() {cout << "heap上對象構造" << endl;SeqStack* ps = new SeqStack(60); // heap malloc內存開辟+SeqStack對象構造ps->push(70);ps->push(80);ps->pop();cout << ps->top() << endl;delete ps; // 先調用ps->~SeqStack()+然后free(ps)cout << "stack上對象構造" << endl;SeqStack s(5); //stackfor (int i = 0; i < 15; ++i) {s.push(rand() % 100);}while (!s.empty()) {cout << s.top() << " ";s.pop();}cout << endl;return 0;
}
打印結果如下:
00007FF7FB3914C0 SeqStack
heap上對象構造
0000026D43E94EF0 SeqStack
70
0000026D43E94EF0 ~SeqStack
stack上對象構造
000000F8EF6FF9D8 SeqStack
61 27 81 45 5 64 62 58 78 24 69 0 34 67 41
000000F8EF6FF9D8 ~SeqStack
00007FF7FB3914C0 ~SeqStack
4、深拷貝和淺拷貝
SeqStack s; // 沒有提供任何構造函數的時候,會為你生成默認構造函數SeqStack s1(10);SeqStack s2 = s1; // #1 默認拷貝構造函數 -》做直接內存數據拷貝//Seqstack s3(s1);// #2 同1
上述默認構造函數導致出現淺拷貝的問題,淺拷貝一般包括以下幾種問題:
-
多個對象共享同一資源:
如果多個對象的指針成員指向同一塊內存,修改其中一個對象會影響其他對象。 -
重復釋放資源:
當多個對象的指針指向同一塊內存時,析構函數可能會多次釋放同一塊內存,導致程序崩潰。 -
內存泄漏:
如果資源被淺拷貝后,原始對象的資源沒有被正確釋放,會導致內存泄漏。
默認拷貝構造函數:淺拷貝
SeqStack(const SeqStack &src) {_pstack = src._pstack;_top = src._top;_size = src._size;}
深拷貝
SeqStack(const SeqStack &src) {_pstack = new int[src._size];for (int i = 0; i <= src._top; ++i) {_pstack[i] = src._pstack[i];}_top = src._top;_size = src._size;}
如果對兩個已經存在的對象進行賦值操作,也會出現淺拷貝問題
int main() {cout << "開始構造s" << endl;SeqStack s; // 沒有提供任何構造函數的時候,會為你生成默認構造函數cout << "開始構造s1" << endl;SeqStack s1(10);cout << "開始構造s2" << endl;SeqStack s2 = s1; // #1 默認拷貝構造函數 -》做直接內存數據拷貝//Seqstack s3(s1);// #2 同1s2 = s1;return 0;
}
s2 = s1; // 默認的賦值函數 =》做直接的內存拷貝
修改如下:
// s2.operator=(s1)
// void operator=(const SeqStack &src)
#include <iostream>
using namespace std;const int NAME_LEN = 20;class SeqStack {
public: SeqStack(int size = 10) {cout << this << " SeqStack" << endl;_pstack = new int[size];_top = -1;_size = size;}// 自定義拷貝構造函數SeqStack(const SeqStack& src) { cout << this << " const SeqStack& src" << endl;_pstack = new int[src._size];for (int i = 0; i <= src._top; ++i) {_pstack[i] = src._pstack[i];}_top = src._top;_size = src._size;}// 賦值重載函數void operator=(const SeqStack& src) {cout << this << " operator=" << endl;// 防止自賦值if (this == &src) {return;}// 需要先釋放當前對象占用的外部資源delete[]_pstack;_pstack = new int[src._size];for (int i = 0; i <= src._top; ++i) {_pstack[i] = src._pstack[i];}_top = src._top;_size = src._size;}~SeqStack() {cout << this << " ~SeqStack" << endl;delete[]_pstack;_pstack = nullptr;}void push(int val) {if (full()) {resize();}_pstack[++_top] = val;}void pop() {if (empty()) {return;}--_top;}int top() {return _pstack[_top];}bool empty() { return _top == -1; }bool full() { return _top == _size - 1; }private:int *_pstack;int _top;int _size;void resize() {int* ptmp = new int[_size * 2];for (int i = 0; i < _size; ++i) {ptmp[i] = _pstack[i];} // memcpy(ptmp, _pstack, sizeof(int)*size);或realloc可能產生深拷貝淺拷貝的問題delete[]_pstack;_pstack = ptmp;_size *= 2;}
};int main() {cout << "開始構造s" << endl;SeqStack s; // 沒有提供任何構造函數的時候,會為你生成默認構造函數cout << "開始構造s1" << endl;SeqStack s1(10);cout << "開始構造s2" << endl;SeqStack s2 = s1; // #1 默認拷貝構造函數 -》做直接內存數據拷貝//Seqstack s3(s1);// #2 同1s2 = s1;return 0;
}
打印結果:
開始構造s
0000003B8E14F6C8 SeqStack
開始構造s1
0000003B8E14F6F8 SeqStack
開始構造s2
0000003B8E14F728 const SeqStack& src
0000003B8E14F728 operator=
0000003B8E14F728 ~SeqStack
0000003B8E14F6F8 ~SeqStack
0000003B8E14F6C8 ~SeqStack
5、構造函數和深拷貝的簡單應用
- 字符串String
#include <iostream>
using namespace std;class String {
public: String(const char* str = nullptr) { // 普通構造函數if (str != nullptr) {m_data = new char[strlen(str) + 1];strcpy_s(m_data, strlen(str) + 1, str);}else {m_data = new char[1];*m_data = '\0';}}String(const String& other) { // 拷貝構造函數m_data = new char[strlen(other.m_data) + 1];strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);}~String() {delete[]m_data;m_data = nullptr;}String& operator=(const String& other) { // 返回值不是void,而是當前類型的引用,是為了連續賦值if (this == &other) {return *this;}delete[]m_data;m_data = new char[strlen(other.m_data) + 1];strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);return *this;}private:char* m_data;
};int main() {// 調用帶const char*參數的構造函數String str1;String str2("hello");String str3 = "world";// 調用拷貝構造函數String str4 = str3;String str5(str4);// 調用賦值重載函數str1 = str2;str3 = str1 = str2; // 連續賦值return 0;
}
- 循環隊列Queue
#include <iostream>
using namespace std;class Queue {
public: Queue(int size = 20) {_pQue = new int[size];_front = _rear = 0;_size = size;}Queue(const Queue &src) {_front = src._front;_rear = src._rear;_size = src._size;_pQue = new int[_size];for (int i = _front; i != _rear; i = (i + 1) % _size) {_pQue[i] = src._pQue[i];}}Queue& operator=(const Queue& src) {if (this == &src) {return *this;}delete[]_pQue;_front = src._front;_rear = src._rear;_size = src._size;_pQue = new int[_size];for (int i = _front; i != _rear; i = (i + 1) % _size) {_pQue[i] = src._pQue[i];}return *this;}~Queue() {delete[]_pQue;_pQue = nullptr;}void push(int val) {// 入隊操作if (full()) {resize();}_pQue[_rear] = val;_rear = (_rear + 1) % _size;}void pop() { // 出隊操作if (empty()) {return;}_front = (_front + 1) % _size;}int front() {return _pQue[_front];}bool full() {return (_rear + 1) % _size == _front;}bool empty() {return _front == _rear;}private:int* _pQue; // 申請隊列的數組空間int _front; // 指示隊頭的位置int _rear; // 指示隊尾的位置int _size; // 隊列擴容的總大小void resize() {int* ptmp = new int[2 * _size];int index = 0;for (int i = _front; i != _rear; i = (i + 1) % _size) {ptmp[index++] = _pQue[i];}delete[]_pQue;_pQue = ptmp;_front = 0;_rear = index;_size *= 2;}
};int main() {Queue q;for (int i = 0; i < 20; ++i) {q.push(rand() % 100);}while (!q.empty()) {cout << q.front() << " ";q.pop();}cout << endl;Queue q1 = q;q1 = q;return 0;
}
6、構造函數的初始化列表
#include <iostream>
using namespace std;class CDate {
public:CDate(int y, int m, int d) { //自定義的構造函數_year = y;_month = m;_day = d;}void show() {cout << _year << "/" << _month << "/" << _day << endl;}private:int _year;int _month;int _day; };/*
構造函數的初始化列表: 可以指定當前對象成員變量的初始化方式
CDate信息 CGoods商品信息的一部分 a part of ... 組合的關系
*/
class CGoods {
public: // "CDate"沒有合適的構造函數可用,因此在這里使用初始化列表CGoods(const char *n, int a, double p, int y, int m, int d): _date(y, m, d), _amount(a) // 相當于int _amount = a;直接進行初始化,// 避免了先定義(int _amount; _amount = a;)需要調用默認構造函數,// 而CDate因為定義了自定義的構造函數,不會調用默認構造函數, _price(p) // #1 構造函數的初始化列表{// #2 當前類類型構造函數體strcpy_s(_name, 20, n);}void show() {cout << "name: " << _name << endl;cout << "amount: " << _amount << endl;cout << "price: " << _price << endl;_date.show();}private:char _name[20];int _amount;double _price;CDate _date; // 成員對象 1.分配內存 2.調用構造函數
};int main() {CGoods good("商品", 100, 35.0, 2025, 1, 27);good.show();return 0;
}
注意:成員變量的初始化和它們定義的順序有關,和構造函數初始化列表中出現的先后順序無關!
#include <iostream>
using namespace std;class Test {
public: Test(int m = 10):mb(m), ma(mb) {}void show() {cout << "ma: " << ma << "mb: " << mb << endl;}private:int ma;int mb;
};int main() {Test t; t.show(); // ma: -858993460 mb: 10return 0;
}
Windows下會將未初始化的內存填充為特定的值0xCCCCCCCC(十進制為-858993460),先初始化ma,而此時mb未初始化,其值-858993460,因此ma: -858993460,而mb: 10。
五、類的各種成員變量和成員方法
1、普通成員變量、靜態成員變量
2、普通成員方法、靜態成員方法、常成員方法
- 普通的成員方法 =>編譯器會添加一個this形參變量
1.屬于類的作用域
2.調用該方法時,需要依賴一個對象!常對象是無法調用的 實參:const CGoods* -》CGoods *this
3.可以任意訪問對象的私有成員 protected繼承 public private - static靜態成員方法 =>不會生成this形參
1.屬于類的作用域
2.用類名作用域來調用方法
3.可以任意訪問對象的私有成員,僅限于不依賴對象的成員(只能調用其它的static靜態成員) - const常成員方法 const CGoods *this
1.屬于類的作用域
2.調用依賴一個對象,普通對象或者常對象都可以
3.可以任意訪問對象的私有成員,但是只能讀,而不能寫(只要是只讀操作的成員方法,一律實現成const常成員方法)
#include <iostream>
using namespace std;const int NAME_LEN = 20;class CGoods {
public:CGoods(const char* name, double price, int amount);void show();void show() const;static void showCount();private:char _name[NAME_LEN];double _price;int _amount;static int _count; // 聲明 用來記錄商品對象的總數量;不屬于對象,而屬于類級別的
};// static成員變量一定要在類外進行定義并且初始化
int CGoods::_count = 0; CGoods::CGoods(const char* name, double price, int amount) {strcpy_s(_name, sizeof(_name), name);_price = price;_amount = amount;_count++; // 記錄所有產生的新對象的數量
}// 普通成員方法 CGoods *this
void CGoods::show() {cout << "name: " << _name << endl;cout << "price: " << _price << endl;cout << "amount: " << _amount << endl;
}// 常成員方法 const CGoods *this
void CGoods::show() const {cout << "name: " << _name << endl;cout << "price: " << _price << endl;cout << "amount: " << _amount << endl;
}// 靜態成員方法 沒有this指針
void CGoods::showCount() {cout << "所有商品數量: " << _count << endl;
}int main() {CGoods good1("面包", 10.0, 200);good1.show();CGoods good2("空調", 100.0, 50);good2.show();CGoods::showCount();const CGoods good3("非賣品", 10000.0, 1);good3.show(); //CGoods::show(&good3) const CGoods* -> CGoods*不可以return 0;
}
六、指向類成員(成員變量和成員方法)的指針
指向普通成員變量的指針依賴于對象的調用,指向靜態成員變量的指針不依賴。
指向普通成員方法的函數指針同樣依賴于對象的調用,指向靜態成員方法的指針不依賴。
#include <iostream>
using namespace std;class Test {
public:void func() { cout << "call Test::func" << endl; }static void static_func() { cout << "Test::static func" << endl; }int ma;static int mb;
};int Test::mb;int main() {Test t1; Test *t2 = new Test();// 指向成員變量的指針// int a=10; int *p=&a; *p=30;int Test::*p = &Test::ma;t1.*p = 20;cout << t1.*p<< endl;t2->*p = 30; cout << t2->*p << endl; // 指向靜態成員變量的指針int *p1 = &Test::mb;*p1 = 40;cout << *p1 << endl;// 指向成員方法的指針void (Test::*pfunc)() = &Test::func; (t1.*pfunc)();(t2->*pfunc)();// 定義函數指針指向類的靜態成員方法void(*pfunc1)() = &Test::static_func;(*pfunc1)();delete t2;return 0;
}
打印結果如下:
20
30
40
call Test::func
call Test::func
Test::static func