C++程式設計方法2:基本文法

來源:互聯網
上載者:User

標籤:return   函數返回   code   val   自動調用   var   基於   基礎   設計   

初始化列表

int a[] = {1,2,3};

int a[]{1,2,3}

以上兩個式子等價

 

int a = 3+5;

int a = {3+5};

int a(3+5);

int a{3+5};

以上式子等價

int *i = new int(10);

double *d = new double{1.2f};

變數的類型推導與基於範圍的迴圈

使用decltype可以對變數或者運算式結果的類型進行推導,如:

#include <iostream>using namespace std;struct {    char *name;}anon_u;struct {    int d;    decltype(anon_u)id;}anon_s[100];//匿名的struct數組int main(){    decltype(anon_s)as;    cin >> as[0].id.name;}

基於範圍的for迴圈語句

基於範圍的for迴圈:在迴圈頭的圓括弧中,由冒號:分為兩部分,第一部分用於迭代的變數,第二個部分用於表示將被迭代的範圍如:

#include <iostream>using namespace std;int main(){    int arr[3] = { 1,3,9 };    for (int e:arr)//for(auto e:arr)    {        cout << e << endl;    }    return 0;}

追蹤傳回型別的函數

可以將函數的傳回型別的聲明資訊放到函數參數列表的後邊進行聲明,如:
普通函數的聲明形式:

int func(char*ptr, int val);

zz追蹤傳回型別的函數的聲明形式:
auto func(char *ptr, int val)->int;

追蹤傳回型別在原本函數傳回值的位置使用auto關鍵字

 

成員函數的定義:類內部定義和類的外部定義

友元

有時候需要允許某些函數訪問對象的私人成員,可以通過聲明該函數為類的“友元”來實現

#include <iostream>using namespace std;class Test{    int id;public:    friend void print(Test obj);};void print(Test obj){    cout << obj.id << endl;}//Test類中聲明了Test類的友元函數print,該函數在實現時可以訪問Test類定義的對象的私人成員;

 

在定義元素為對象的數組(ClassName array_var[NUM];)時,類必須提供預設建構函式的定義;

 

在建構函式的初始化列表中,還可以調用其他建構函式,被稱為“委派建構函式”

class Info{public:    Info() { Init(); }    Info(int i) :Info() { id = i; }    Info(char c) :Info() { gender = c; }private:    void Init(){}    int id{ 2016 };    char gender{ ‘M‘ };};

拷貝建構函式

函數調用時以類的對象為形參或者返回類的對象時,編譯器會產生自動調用“拷貝建構函式”,在已有對象基礎上產生新的對象;

 

拷貝建構函式是一種特殊的建構函式,他的參數是語言規定的,是同類對象的常量引用;

語義上:用參數對象的內容初始化當前對象

class Person

{

int id;

public:
person(const Person &src) {id = src.id;}

}

拷貝建構函式的例子:

#include <iostream>using namespace std;class Test{public:    Test() { cout << "Test()" << endl; }    Test(const Test& src) { cout << "Test(const Test&)" << endl; }    ~Test() { cout << "~Test()" << endl; }};void func1(Test obj){    cout << "func1()" << endl;}Test func2(){    cout << "func2()" << endl;    return Test();}int main(){    cout << "main()" << endl;    Test t;    func1(t);    t = func2();    return 0;}

 

C++程式設計方法2:基本文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.