【问题标题】:why I can pass a reference to derived class object to base class constructor without any compiling error?为什么我可以将对派生类对象的引用传递给基类构造函数而没有任何编译错误?
【发布时间】:2018-07-13 05:46:00
【问题描述】:

在 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;
}

输出

 A constructor called
 B default constructor called
 B constructor called

【问题讨论】:

标签: c++ inheritance constructor copy-constructor default-constructor


【解决方案1】:

A(b)调用A中的拷贝构造函数,编译器已经为你提供了。

自己写出来看看

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

在课堂上A。这都是完美定义的 C++。

【讨论】:

  • @WubinOuyang:回答你自己的问题没有坏处。
【解决方案2】:

我问了五分钟后就想通了。它实际上是调用由编译器创建的 A 的复制构造函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多