[英]Replace default copy constructor with copy constructor for base class (c++)
[英]c++ what does Derived Default copy constructor initialize Base copy constructor with?
碼:
#include<iostream>
using namespace std;
class B{
public:
int b;
B(int x):b(x){
cout << "B() Constructor " << endl;}
B(const B& m):b(m.b){
cout << "B(const B&) copy constructor "<< endl;}
};
class D:public B{
public:
D(int x):B(x){
cout << "D() Constructor " << endl;}
D(const D& n):B(n){ // at this point n should be casted to B object !!?
cout << "D(const D&) copy constructor " << endl;}
operator B(){
cout << "operator B" << endl;
return B(this->b);}
};
int main(){
D ob(1);
cout << "---" << endl;
D oc=ob;
}
輸出:
B() Constructor
D() Constructor
---
B(const B&) copy constructor
D(const D&) copy constructor
問題:
1)如果我不提供我的D
的拷貝構造函數,默認拷貝構造函數D
必須通過調用初始化基對象B
拷貝構造函數。 我的問題是B
復制構造函數將采用什么參數? 是D
對象,然后將其轉換為B
對象嗎?
2)在D
的副本構造函數中,我使用D
對象n
初始化了B
,並且沒有調用operator B()
來證明類型D
的對象n
沒有被強制轉換為B
,因此可以作為參數傳遞給B
復制構造函數。 有這種現象的任何解釋嗎?
首先, 強制類型轉換是您在代碼中編寫的,用於告訴編譯器進行轉換。 轉換分為兩類:隱式轉換和顯式轉換。 隱式轉換將在需要時進行,而無需強制轉換。 顯式轉換需要強制轉換。 您在這里所說的是隱式轉換 ,而不是強制轉換 。
答案是,存在從對派生類型的引用到對基本類型的引用的隱式轉換。 就是這么簡單:n是D&,可以通過隱式轉換其類型將其傳遞給采用B&的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.