0

如果我有一些类,并且在那个类中我有一个自定义的 Queue 对象,我已经编写了,我的类 def 看起来像这样:

class Parser
{
    public:
        Parser();
    private:
        Queue<char> Q;
};

并且class Queue有一个默认构造函数以及一个接受单个 int 参数来指定其容量的构造函数,我如何告诉 Parser 类当它实例化 Q 字段时它应该触发接受参数的构造函数(所以它可以有一个更大容量)而不是触发默认构造函数(容量很小)?我已经查过了,但我很难找到不围绕继承和父类构造函数的答案。谢谢!

另外,我尝试替换Queue<char> Q为,Queue<char> Q(100)但编译器抱怨这一点。

4

3 回答 3

2

在 Parser 的构造函数实现中使用初始化列表...

Parser::Parser()
:Q(10) ///example of initializing to capacity 10
{
}
于 2013-02-18T19:14:10.740 回答
1

它位于您选择构造函数的成员初始化列表中:

  • 如果要调用默认构造函数,请执行以下操作:

    Parser() : Q() {} //calls the default constructor
    

    由于您没有传递任何参数,因此上述内容与以下内容相同:

     Parser() {} //Q is also constructed invoking the default constructor
    

    在进入Parser构造函数体之前,完全Q是通过调用默认构造函数来构造的。

  • 如果要调用另一个构造函数,请执行以下操作:

    Parser() : Q(10) {} //calls the other constructor
    

    这就是你想要的。在这种情况下,您通常希望将大小传递给Parser然后执行此操作:

    Parser(int size) : Q(size) {} //calls the other constructor
    

在 C++11 中,您可以在声明本身中这样做:

class Parser
{
     //...
     Queue<char> Q(10); //C++11 only
};
于 2013-02-18T19:14:06.107 回答
1

像这样:

Parser() : Q(100) { }
于 2013-02-18T19:14:05.903 回答