私下继承时的构造函数继承和多态性

发布于 2025-01-29 03:21:41 字数 1118 浏览 0 评论 0原文

我正面临着继承的难题。我正在使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文