簡體   English   中英

當我們在派生的 class 中編寫空的復制構造函數時會發生什么?

[英]What happen when we write empty copy constructor in derived class?

#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int );
};

A::A(int arg) {
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}

// Class B is derived from A
class B: A {
public:
    B(int );
    B(const B& ref)
    {
        cout<<"copy constructor get called"<<endl;
    }
};

B::B(int x):A(x) { //Initializer list must be used
    cout << "B's Constructor called";
}

int main() {
    B obj(10);
    return 0;
}
output:
prog.cpp: In copy constructor ‘B::B(const B&)’:
prog.cpp:20:2: error: no matching function for call to ‘A::A()’
  {
  ^
prog.cpp:10:1: note: candidate: A::A(int)
 A::A(int arg) {
 ^
prog.cpp:10:1: note:   candidate expects 1 argument, 0 provided

添加復制構造函數時出現上述錯誤。 當我刪除復制構造函數時,錯誤已解決。 任何人都可以解釋為什么我在復制構造函數中出現錯誤,甚至沒有使用復制構造函數創建 object 嗎?

即使您不使用B的復制構造函數,它仍然必須有效。

目前它不會從A調用任何構造函數,因此它將默認使用默認構造函數構造基本 class 。

由於沒有默認構造函數,因此您會收到錯誤消息。

您已經定義了一個顯式的空復制構造函數,但它沒有任何成員初始化列表

默認情況下,編譯器將在成員初始化列表中調用A::A()

B(const B& ref): A()
{
    std::cout << "copy constructor get called" << std::endl;
}

因為,沒有不帶任何參數的A默認構造函數。 編譯器拋出錯誤:

error: no matching function for call to ‘A::A()’

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM