c++雜項備忘

來源:互聯網
上載者:User

<摘自C++Primer>

const

修飾變數,則該變數初始化的時候被賦值,在程式運行過程中不能被修改

非const變數預設為extern,要使const變數能夠在其他的檔案中訪問,必須顯式地指定它為extern.

const 引用是指向const對象的引用,並且只能引用該對象的值,而不能改變它的值

<摘自孫鑫VC++深入詳解>

const char * 和char * const

很多和檔案操作相關的函數其參數類型都是const char*(指向常量的指標)與指標常量(char * const)這兩種類型。

const 在*前:表示指向常量的指標,該指標不能修改其指向的記憶體中的內容,但可以修改其所指向的記憶體位址

如 char ch[5]="lisi";

const char * pStr=ch

*pStr='w' //error

pStr="wangwu"//ok

char * const : const在*的後面表指標常量,對於指標常量必須在其定義的同事賦值。指標常量表示指標本身是常量。

char *const pStr=ch;

pStr="zhangsan"//error

*pStR='W'//OK

<摘自徐惠民C++>

常成員函數

文法格式:

傳回值類型說明符 函數名(參數表)const

特點:const是函數類型的一個組成部分,在函數定義,聲明,實現時也要帶const關鍵字。

   常成員函數不能更新對象的資料成員,也不能調用該類中的非常成員函數

   常對象只能調用常成員函數,但是常成員函數也可以被普通對象調用

   const 關鍵字可以被用於參與對重載函數的區分

  

 《摘自C++Reference》

include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
 int end;
 int myints[]={10,20,30,40};
 int *p;
 p=find(myints,myints+4,30);
 p++;
 cout<<"The element following 30 is"<<*p<<endl;
 vector<int> myvector(myints,myints+4);
 vector<int>::iterator it;
 it=find(myvector.begin(),myvector.end(),30);
 it++;
 cout<<"The element following 30 is"<<*it<<endl;

 cin>>end;
 return 0;
}

此段代碼錶明iterator和指標的關係,數組與對應類別vector的關係

建構函式初始化式:只能在建構函式定義而非聲明中指定,沒有預設建構函式的類類型成員,以及const或參考型別的成員,不管是那種類型,都必須在建構函式初始化列表中進行初始化。成員在建構函式初始化列表中被初始化的次序是定義 成員的次序。

 

vector通過下標不能對其賦值,只能通過push_back(),但是map以及二維vector即包含vector的vector可以通過下標來賦值。

如下代碼是合法的

 

vector<vector<int>> myintegers;
   myintegers.resize(3);
   for(int i=0;i<3;i++)
   {
    myintegers[i].resize(4);
   }
   for(int i=0;i<3;i++)
   {
    for(int j=0;j<4;j++)
    {
     myintegers[i][j]=numeric_limits<int>::min();
    }

   }
   for(int i=0;i<3;i++)
   {
    for(int j=0;j<4;j++)
    {
    cout<< myintegers[i][j];
    }
    cout<<endl;

   }

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.