本文實例講述了C++實現(xiàn)動態(tài)分配const對象的方法。分享給大家供大家參考。具體方法分析如下:
一、創(chuàng)建
在C++中,允許動態(tài)創(chuàng)建const對象,格式如下:
1
|
const int *p = new const int (128); |
與其他常量一樣,動態(tài)創(chuàng)建的const對象必須在創(chuàng)建時初始化,并且初始化后,其值不能改變。
二、刪除
盡管不能改變const對象的值,但可以刪除動態(tài)創(chuàng)建的const對象,格式如下:
1
|
delete p; |
這個和普通的對象一樣,可以對其進行刪除操作。
三、應用場景舉例
1、加載配置文件
從配置文件讀入的數(shù)據(jù)可以用來初始化const對象,供后續(xù)程序使用。
偽代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
int num; ... //讀取配置文件,并將配置數(shù)據(jù)填充到num const int *pNum = new const int (num); // 用num初始化const對象 cout<<*pNum<<endl; //使用const對象 ... delete pNum; |
2、創(chuàng)建數(shù)組
當數(shù)組的大小依賴于某些動態(tài)因素時(比如配置文件等),可以考慮用const對象。
偽代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
int num; ... //獲取num的值 const int *pNum = new const int (num); // 用num初始化const對象 unsigned char _data[*pNum]; //創(chuàng)建數(shù)組 ... delete pNum |
示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#include <iostream> using namespace std; int main() { int num; cin>>num; const int *pNum = new const int (num); int arr[*pNum]; for ( int i=0;i<*pNum;++i) arr[i] = i; for ( int i=0;i<*pNum;++i) cout<<arr[i]<< " " ; cout<<endl; return 0; } |
當然還有很多其它場景,這里暫時記錄了這些,方便以后查閱。
希望本文所述對大家的C++程序設計有所幫助。