複製建構函式和 運算子過載的區別

2021-06-29 10:02:00 字數 2585 閱讀 6074

如果乙個類定義了複製建構函式,同時又過載了=操作符,那麼兩個有以下區別,複製建構函式是在類初始化時使用,而=運算子則是在初始化以後被呼叫,例如以下**

test test;

test test1(test);

test1 =test;

上面第一行**,呼叫test的預設建構函式

第二行**呼叫test的複製建構函式

第三行**呼叫test的=過載操作符的運算

我們可以通過以下的類來說明兩者的區別

copyconstructtest類

#pragma once

#include

#include "testchild.h"

using

namespace

std;

class copyconstructtest

;#include "copyconstructtest.h"

#include "testchild.h"

copyconstructtest::copyconstructtest(void)

// 複製建構函式

// 先呼叫testchild的建構函式,在呼叫本類的建構函式

copyconstructtest::copyconstructtest(const copyconstructtest& arg):testchild(arg.testchild)

// 賦值操作符

copyconstructtest ©constructtest::operator=(const copyconstructtest& arg)

testchild類

#pragma once

class testchild

;#include "testchild.h"

#include

using

namespace

std;

testchild::testchild(void)

testchild::testchild(const testchild &testchild)

explicit類,用於測試explicit關鍵字的作用

#pragma once

#include

#include

using

namespace

std;

class explicittest

;#include "explicittest.h"

explicittest::explicittest(void)

explicittest::explicittest(string name)

explicittest::~explicittest(void)

bool explicittest::samename(const explicittest& test)

主函式

#include 

#include

#include "copyconstructtest.h"

#include "explicittest.h"

using

namespace

std;

void showmenu();

void main()

break;

case

1:

break;

default:

break;}}

system("pause");

}void showmenu()

選擇不同的注釋段,實現的結果是不一樣的

再說說explicit關鍵字,他的主要作用是防止隱式轉換

比如在以下幾行**

explicittest::explicittest(string name)

explicittest::~explicittest(void)

bool explicittest::samename(const explicittest& test)

如果explicittest::explicittest(string name);建構函式不加explicit識別符號,那麼在呼叫samename函式時,可以這樣呼叫,例如主程式main中的

explicittest extest;

explicittest extest1("中國");

extest.samename(string("中國"));

此時extest.samename(string(「中國」));samename是將string(「中國」)作為引數傳入乙個臨時explicittest物件的建構函式,因為它支援傳入乙個string引數的建構函式,構造乙個臨時的explicittest物件,傳給samename函式中作為引數,但是如果explicittest(string)建構函式用關鍵字explicit修飾,那麼編譯器將會報錯,可以執行一下試試,他必須傳入乙個explicittest物件。

C 複製建構函式和賦值運算子過載函式

宣告乙個空的類testsize,sizeof testsize 為1,為其宣告建構函式和析構函式,依舊為1 建構函式不能使用關鍵字virtual,析構函式可以 一旦類中存在虛函式,就會為該類生成虛函式表,並在每乙個例項中新增乙個指向虛函式表的指標,從而大小為乙個指標大小,32位機器上為4,64位機器...

C 複製建構函式,過載賦值運算子

c 的複製建構函式,賦值建構函式,有時候會有點暈,下面總結一下 首先來談一下複製建構函式 includeusing namespace std include includeclass a void fuction void show int main 解釋 定義了乙個類,資料成員有字元指標,和整型...

C 之拷貝建構函式和複製運算子過載

1 c 拷貝建構函式 拷貝建構函式是為了解決如神明物件時候就用乙個已經存在的物件來初始化這個新的物件,如mystring a b 這裡b是已經存在mystring物件。但是這裡需要注意拷貝建構函式裡面的內部實現細節。這裡面其實是在這個a物件類的定義中定義了拷貝建構函式的格式如 mystring co...