C++ 为什么我可以将对派生类对象的引用传递给基类构造函数而不会出现任何编译错误?

C++ 为什么我可以将对派生类对象的引用传递给基类构造函数而不会出现任何编译错误?,c++,inheritance,constructor,copy-constructor,default-constructor,C++,Inheritance,Constructor,Copy Constructor,Default Constructor,在类A中,我没有定义任何接受参数的构造函数。在类B中,它是类a的派生类,我定义了一个复制构造函数,它将B的引用传递给a的构造函数。看到这段代码确实通过了编译,输出如下,真是太奇怪了。有人能解释一下吗 // Example program #include <iostream> #include <string> class A{ public: A(){ std::cout<<"A constructor called"<<std::

在类A中,我没有定义任何接受参数的构造函数。在类B中,它是类a的派生类,我定义了一个复制构造函数,它将B的引用传递给a的构造函数。看到这段代码确实通过了编译,输出如下,真是太奇怪了。有人能解释一下吗

// Example program
#include <iostream>
#include <string>

class A{
  public:
    A(){ std::cout<<"A constructor called"<<std::endl;};
    ~A(){};
};

class B:private A{
  public:
    B(){std::cout<<"B default constructor called"<<std::endl;};

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

int main()
{
  B b{};
  B b2{b};
  return 0;
}
Ab在A中调用复制构造函数,该构造函数是由编译器为您提供的

通过写作自己看

A(const A& a) {std::cout << "A copy constructor called\n";}

在A类中,这都是完全定义的C++。

< P>我在问了五分钟后就明白了。它实际上是调用一个由编译器创建的复制构造函数

我不认为这个问题很糟糕。它写得很好,有示例代码,并且给出了输出。@WubinOuyang:回答你自己的问题没有坏处。
A(const A& a) {std::cout << "A copy constructor called\n";}