1. 程式人生 > >一個關於C++拷貝構造的bug

一個關於C++拷貝構造的bug

{} return color system turn out stream efault col

#include <iostream>
using namespace std;

class A {
public:
    A(int a) {};
    A(const A&) = default;
}; 

class B : public A{
public:
    B(int b) : A(b) {};
    B(const A& a) : A(a){
        cout << "B copy construction" << endl;
    };
//B(const B&) = delete; };
class C : public A{ public: C(int c) : A(c) {}; C(const A& a) : A(a) { cout << "C copy construction" << endl; }; }; int main() { B b1(1); C c1(1); B b2(b1); B b3(c1); system("pause"); return 0; }

用C對象構造B對象是可以的,但是為啥用B對象構造B就沒有輸出“B copy construction”呢?原來B(const A& a) 並不被認為是拷貝構造函數,編譯器還會生成默認的B(const B&)拷貝構造,B b2(b1)實際調用的是B(const B&),而不是聲明的B(const A& a)函數。這時如果禁用默認拷貝構造B(const B&) = delete;就會發現編譯不過。

一個關於C++拷貝構造的bug