私下继承时的构造函数继承和多态性
我正面临着继承的难题。我正在使用C ++ 20。 如果我在其中一个从另一个继承,并使继承本身私有,但仍然公开声明构造函数,则该代码不会汇编:
https://godbolt.org/z/6z9p6svpvpv
#include <iostream>
class Base { };
class FirstChild : private Base {
public:
using Base::Base;
};
void foo(Base* base) {
std::cout << "Not ok!" << std::endl;
}
int main() {
auto derived = new FirstChild();
foo(derived);
}
但是,如果我经历了更多遗传; Child2),尽管我的IDE(Clion)对我大喊这是一个错误,但它似乎是编译并工作正常。
https://godbolt.org/z/nmdf5v7y5
#include <iostream>
class Base { };
class FirstChild : public Base { };
class SecondChild : private FirstChild {
public:
using FirstChild::Base;
};
void foo(Base* base) {
std::cout << "Ok!" << std::endl;
}
int main() {
auto derived = new SecondChild();
foo(derived);
}
我不确定有什么问题。为什么第二件代码可以工作,但第一个代码不行?第二个实际上是正确的吗?它确实编译了,但是正如我所说,我的IDE对此不满意。
I'm facing a bit of a puzzle with inheritance. I'm using c++ 20.
If i make 2 classes (Base -> Child1), where one inherits from the other, and make the inheritance itself private, but still declare the constructors publicly inherited, then this piece of code doesn't compile:
https://godbolt.org/z/6z9P6svPv
#include <iostream>
class Base { };
class FirstChild : private Base {
public:
using Base::Base;
};
void foo(Base* base) {
std::cout << "Not ok!" << std::endl;
}
int main() {
auto derived = new FirstChild();
foo(derived);
}
However if i go through one more inheritance (Base -> Child1 -> Child2), and despite my IDE (Clion) shouting at me that this is an error, it seems to compile and work just fine.
https://godbolt.org/z/nMdf5v7Y5
#include <iostream>
class Base { };
class FirstChild : public Base { };
class SecondChild : private FirstChild {
public:
using FirstChild::Base;
};
void foo(Base* base) {
std::cout << "Ok!" << std::endl;
}
int main() {
auto derived = new SecondChild();
foo(derived);
}
I'm not sure what's the problem. Why does the second piece of code work but the first one doesn't? And is the second one actually correct? It does compile, but as i said, my IDE isn't very happy with it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论