【发布时间】: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