C++ 中的基于成员的习语
以下代码来自此处:
#include <streambuf> // for std::streambuf
#include <ostream> // for std::ostream
class fdoutbuf
: public std::streambuf
{
public:
explicit fdoutbuf( int fd );
//...
};
class fdostream
: public std::ostream
{
protected:
fdoutbuf buf;
public:
explicit fdostream( int fd )
: buf( fd ), std::ostream( &buf ) // This is not allowed.
// buf can't be initialized before std::ostream.
{}
//...
};
我没有真的很理解评论。为什么“buf 不能在 std::ostream 之前初始化”?我可以使用一些帮助来理解这一点吗?
The following code is from here:
#include <streambuf> // for std::streambuf
#include <ostream> // for std::ostream
class fdoutbuf
: public std::streambuf
{
public:
explicit fdoutbuf( int fd );
//...
};
class fdostream
: public std::ostream
{
protected:
fdoutbuf buf;
public:
explicit fdostream( int fd )
: buf( fd ), std::ostream( &buf ) // This is not allowed.
// buf can't be initialized before std::ostream.
{}
//...
};
I didn't really understand the comment. Why "buf can't be initialized before std::ostream"? Can I use some help understanding this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
初始化的顺序由声明类成员的顺序决定,继承的类位于所有这些之前。举一个简单的例子来说明基本问题,而不涉及继承:
代码没有按照你的想法做!首先a被初始化,然后b被初始化为1。因此,它取决于声明的顺序而不是初始化列表中的顺序:
现在,相同的想法适用于在派生类成员之前初始化的基类。为了解决这个问题,您创建一个您固有的类,其中包含您想要从基类初始化的成员。当然,该辅助类必须位于您实际派生的辅助类之前。
The order of initialization is determined by the order of declaring your class members, and inherited classes come before all of that. Take a simple example that illustrate the basic problem without referring to inheritance :
The code doesn't do what you think! a is initialized first, then b is initialized to one. So it depends on the order of the declaration not the order in the initialization list:
Now, the same idea applies to base classes which are initialized before the derived class members. To solve this problem, you create a class that you inherent which contains the member you want to initialize from a base class. Of course, that helper class must come before the one you are actually deriving from.
在初始化成员变量之前,您必须调用基类构造函数,但您将指向 buf 的指针(此时未定义的成员变量)传递给此构造函数。
You have to call the base class constructor before you initialize your member variables, but you pass a pointer to buf (a member variable which is undefined at this point) to this constructor.