【问题标题】:How constructor works in private inheritance构造函数在私有继承中的工作原理
【发布时间】:2015-07-11 13:09:05
【问题描述】:

我知道关于这个话题有同样的问题。但我还是很困惑。请解释 A 的类构造函数是如何使用obj 执行的,即使我私下继承了 A 的类构造函数。

#include <iostream>
using namespace std;
class A{
    public:
        A(){
            cout << "A" << endl;
        }
};
class B:private A{
    public:
        B(){
            cout << "B" << endl;
        }
};
int main(){
    B obj;

    return 0;
}

输出

A
B

【问题讨论】:

    标签: c++ inheritance access-specifier


    【解决方案1】:

    私有继承意味着所有公共和受保护的基成员在派生类中变为私有。所以A::A()B 中是私有的,因此可以从B::B() 完全访问。

    B::B() 不能使用的是 Aprivate 构造函数(但你没有这些构造函数):

    struct A
    {
    public:
        A();
    protected:
        A(int);
    private:
        A(int, int);
    };
    
    struct Derived : /* access irrelevant for the question */ A
    {
        Derived() : A() {}      // OK
        Derived() : A(10) {}    // OK
        Derived() : A(1, 2) {}  // Error, inaccessible
    };
    

    【讨论】:

    • 你能解释一下我给定的例子是如何工作的吗?我的意思是你能在我给定的例子中告诉我后台处理的代码吗?
    • @LetDoit:我不太明白你的问题。您对B::B() 的定义意味着A 子对象的默认构造;如果你写了B::B() : A() { /* your code */ },就像你一样。
    • 在我的示例中B( ) 隐式调用A 类的默认构造函数?如。 B() : A() { }
    • @LetDoit:这不是我刚才说的吗?
    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    相关资源
    最近更新 更多