[英]Explicitly calling base class constructor in derived class
请问是否可以在derived class中显式调用base class构造函数? (如果不是,为什么?)
我问这个问题是因为我写了下面的玩具代码,结果让我很困惑:
class X
{
public:
void wow()
{
cout << "wow\n";
}
protected:
X()
{
cout << "creating X\n";
}
X(int i)
{
cout << "creating X with i\n";
}
};
class Y : protected X
{
public:
X r = X{ 1 }; // error at this line: (C2248) 'X::X': cannot access protected member declared in class 'X'
};
int main()
{
Y y;
y.r.wow();
}
但是,如果我在class Y
中稍作修改,代码实际上可以编译:
// X defined same as above...
class Y : protected X
{
public:
X r = { 1 };
};
int main()
{
Y y; // creating X
// creating X with i
y.r.wow(); // wow
}
我正在使用 Visual Studio 2022。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.