考虑这个示例代码:
#include <iostream>
class base {
public:
base() {
std::cout << "base constructed" << std::endl;
}
base(const base & source) {
std::cout << "base copy-constructed" << std::endl;
}
};
class derived : public base {
public:
derived() {
std::cout << "derived constructed" << std::endl;
}
derived(const derived &) = delete;
derived(const base & source) : base(source) {
std::cout << "derived copy-constructed from base" << std::endl;
}
};
int main() {
derived a;
base b(a);
derived c(a);
return 0;
}
为什么调用 tobase::base(const base &)
可以,但调用 toderived::derived(const base &)
不行?两者都期望一个基本引用,并且都给出了一个派生引用。我的理解是派生的'是'基础。
为什么编译器在提供对派生类型对象的引用时derived::derived(const derived &)
使用没有问题时坚持使用?base::base(const base &)