构造函数在私有继承中的作用 [英] How constructor works in private inheritance
本文介绍了构造函数在私有继承中的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这个话题也有同样的问题。但我还是困惑。请解释A的类构造函数是否以 obj
执行,即使我继承了A的类构造函数。
code> #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
解决方案>
私有继承意味着所有 public和protected base成员在派生类中成为私有。因此 A :: A()
是 B
中的私有,因此可以从 B :: B()
。
不使用
A
的私有构造函数(但您没有任何这些):
struct A
{
public:
A();
protected:
A(int);
private:
A(int,int);
};
struct Derived:/ *访问与问题无关* / A
{
Derived():A(){} // OK
Derived A(10){} // OK
Derived():A(1,2){} //错误,无法访问
};
I know there are same question about this topic. But I'm still confused. Please explain how A's class constructor is executing with obj
even I inherit A's class constructor privately.
#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;
}
Output
A
B
解决方案
Private inheritance means that all public and protected base members become private in the derived class. So A::A()
is a private in B
, and thus perfectly accessible from B::B()
.
What B::B()
can't use are private constructors of A
(but you don't have any of those):
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
};
这篇关于构造函数在私有继承中的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文