国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++類中的特殊成員函數(shù)示例詳解

2020-01-26 13:32:43
字體:
供稿:網(wǎng)友

前言

C++類中有幾個(gè)特殊的非靜態(tài)成員函數(shù),當(dāng)用戶未定義這些函數(shù)時(shí),編譯器將給出默認(rèn)實(shí)現(xiàn)。C++11前有四個(gè)特殊函數(shù),C++11引入移動(dòng)語義特性,增加了兩個(gè)參數(shù)為右值的特殊函數(shù)。這六個(gè)函數(shù)分別是:

1、默認(rèn)構(gòu)造函數(shù)

默認(rèn)構(gòu)造函數(shù)指不需要參數(shù)就能初始化的構(gòu)造函數(shù)。包含無參和所有參數(shù)有默認(rèn)值兩種類型的構(gòu)造函數(shù)。

2、復(fù)制構(gòu)造函數(shù)

復(fù)制構(gòu)造函數(shù)指使用該類的對(duì)象作為參數(shù)的構(gòu)造函數(shù)。可以有其他參數(shù),但必須提供默認(rèn)值。

3、復(fù)制賦值運(yùn)算符

重載等號(hào)=,將該類的對(duì)象賦值給已定義對(duì)象。

4、析構(gòu)函數(shù)

沒啥可說的。

5、移動(dòng)構(gòu)造函數(shù)

C++11新增,該類的右值對(duì)象為參數(shù)的構(gòu)造函數(shù),其余同復(fù)制構(gòu)造函數(shù)。

6、移動(dòng)復(fù)制運(yùn)算符

同復(fù)制賦值運(yùn)算符,唯一不同是參數(shù)為右值。

看定義容易迷糊,上代碼就會(huì)很清晰:

#include <iostream>#include <string>class Foo {public: std::string s; // 默認(rèn)構(gòu)造函數(shù) Foo() { std::cout << "default constructor" << std::endl; } // 復(fù)制構(gòu)造函數(shù) Foo(const Foo& foo) { std::cout << "copy constructor" << std::endl; s = foo.s; } // 復(fù)制賦值運(yùn)算符 Foo& operator=(const Foo& foo) { std::cout << "copy assignment operator" << std::endl; s = foo.s; return * this;} // 移動(dòng)構(gòu)造函數(shù) Foo(Foo&& foo) { std::cout << "move constructor" << std::endl; s = std::move(foo.s); } // 移動(dòng)賦值運(yùn)算符 Foo& operator=(Foo&& foo) { std::cout << "move assignment operator" << std::endl; s = std::move(foo.s); return *this;}};int main() { Foo foo1; Foo foo2(foo1); foo1 = foo2; Foo foo3(std::move(foo1)); foo2 = std::move(foo3);}

用g++或者clang編譯,加上-fno-elide-constructors -std=c++0x選項(xiàng)。執(zhí)行程序輸出如下:

default constructor
copy constructor
copy assignment operator
move constructor
move assignment operator

結(jié)果是我們預(yù)期的。需要注意的是Foo foo3 = foo1的形式會(huì)調(diào)用復(fù)制構(gòu)造函數(shù),不會(huì)調(diào)用復(fù)制賦值運(yùn)算符。原因是Foo foo3 = xxx聲明和定義一個(gè)新對(duì)象,而賦值是作用在已定義對(duì)象。移動(dòng)賦值運(yùn)算符同理。

C++11新增了=default和=delete函數(shù)修飾符,提示編譯器使用默認(rèn)或者刪除默認(rèn)的特殊函數(shù)。需要注意的是這兩個(gè)修飾符只能修飾上述特殊函數(shù),用戶可以用其對(duì)特殊函數(shù)進(jìn)行裁剪。一個(gè)例子:

struct Test { // 使用默認(rèn)構(gòu)造函數(shù) Test() = default; // 刪除復(fù)制賦值運(yùn)算符 Test& operator=(const Test& test) = delete; // 使用默認(rèn)析構(gòu)函數(shù) ~Test() = default;};

參考

  • https://en.cppreference.com/w/cpp/language/member_functions
  • https://stackoverflow.com/questions/43349808/extended-lifetime-of-an-object-returned-from-function

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)武林網(wǎng)的支持。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 井研县| 商丘市| 西林县| 道孚县| 建瓯市| 保定市| 余姚市| 南川市| 佛学| 铅山县| 奉节县| 湟中县| 云林县| 普安县| 都兰县| 武山县| 鹿泉市| 吐鲁番市| 宜兰市| 丘北县| 洛宁县| 稷山县| 连州市| 潜山县| 玛曲县| 始兴县| 靖宇县| 砚山县| 嘉义县| 台安县| 汉寿县| 昌邑市| 莱州市| 锦屏县| 海口市| 武山县| 班戈县| 九江县| 乌拉特后旗| 东莞市| 漳州市|