C++ 中的基于成员的习语

发布于 2024-10-14 06:24:51 字数 706 浏览 4 评论 0原文

以下代码来自此处

#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 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只为一人 2024-10-21 06:24:51

初始化的顺序由声明类成员的顺序决定,继承的类位于所有这些之前。举一个简单的例子来说明基本问题,而不涉及继承:

class C
{
  int a, b;
public:
  C() : b(1), a(b) {} // a is initialized before b!
};

代码没有按照你的想法做!首先a被初始化,然后b被初始化为1。因此,它取决于声明的顺序而不是初始化列表中的顺序:

int a, b;

现在,相同的想法适用于在派生类成员之前初始化的基类。为了解决这个问题,您创建一个您固有的类,其中包含您想要从基类初始化的成员。当然,该辅助类必须位于您实际派生的辅助类之前。

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 :

class C
{
  int a, b;
public:
  C() : b(1), a(b) {} // a is initialized before b!
};

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:

int a, b;

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.

々眼睛长脚气 2024-10-21 06:24:51

在初始化成员变量之前,您必须调用基类构造函数,但您将指向 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文